text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide a correct Python 3 solution for this coding contest problem.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
"Correct Solution:
```
while True:
n=int(input())
if n==0:
break
x=[]
for i in range(n):
y=int(input())
x.append(y)
for j in range(10):
a=x.count(j)
if a==0:
print("-")
else:
print(a*"*")
```
| 96,000 |
Provide a correct Python 3 solution for this coding contest problem.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
"Correct Solution:
```
while True:
n=int(input())
if n==0:
break
l=[0]*10
for i in range(n):
c=int(input())
l[c] +=1
for j in l:
if j==0:
print("-")
else:
for k in range(j):
print("*",end='')
print('')
```
| 96,001 |
Provide a correct Python 3 solution for this coding contest problem.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
"Correct Solution:
```
# coding: utf-8
# Your code here!
while True :
n = int(input())
if n == 0 :
break
cnt = list([0] * 10)
for i in range(n) :
cnt[int(input())] += 1
for i in range(10) :
if cnt[i] > 0 :
for j in range(cnt[i]) :
print("*", sep="", end="")
print()
else :
print("-")
```
| 96,002 |
Provide a correct Python 3 solution for this coding contest problem.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
"Correct Solution:
```
y=[0,1,2,3,4,5,6,7,8,9]
while True:
n=int(input())
if n==0:
break
x=[]
z=[0,0,0,0,0,0,0,0,0,0]
for i in range(n):
c=int(input())
x.append(c)
# print(x)
for i in range(10):
for j in x:
if y[i]==j:
z[i]+=1
# print(z)
for k in range(10):
if z[k]==0:
print('-')
else:
for l in range(z[k]):
print('*',end='')
print()
```
| 96,003 |
Provide a correct Python 3 solution for this coding contest problem.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
"Correct Solution:
```
while True:
n = int(input())
if n == 0:
break
a = [0] * 10
for i in range(n):
c = int(input())
a[c] += 1
for c in a:
if c == 0:
print('-')
else:
print('*'*c)
```
| 96,004 |
Provide a correct Python 3 solution for this coding contest problem.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
"Correct Solution:
```
import sys
f = sys.stdin
from collections import Counter
while True:
n = int(f.readline())
if n == 0:
break
counter = Counter(int(f.readline()) for _ in range(n))
for i in range(10):
print('*' * counter[i] if 0 < counter[i] else '-')
```
| 96,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
Submitted Solution:
```
while True:
n=int(input())
list=[]
if n==0:
break
else:
for i in range (n):
c=int(input())
list.append(c)
for i in range (0,10):
x=list.count(i)
if x==0:
print("-")
else:
print("*"*x)
```
Yes
| 96,006 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
Submitted Solution:
```
while True :
n = int(input())
if n == 0 : break
numList = [0 for i in range(10)]
for i in range(n) :
c = int(input())
numList[c] += 1
for i in range(10) :
cnt = '*' * numList[i]
if len(cnt) == 0 : print("-")
else : print(cnt)
```
Yes
| 96,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
Submitted Solution:
```
while True:
n=int(input())
if n==0:
break
m=[0 for i in range(10)]
for i in range(n):
a=int(input())
m[a]+=1
for a in m:
if a>0:
print("*"*a)
else:
print("-")
```
Yes
| 96,008 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
Submitted Solution:
```
while 1:
n=int(input())
if n==0:
break
x=[0 for i in range(10)]
for i in range(n):
c=int(input())
x[c]+=1
for i in range(10):
count='*'*x[i]
if len(count)==0:
print("-")
else:
print(count)
```
Yes
| 96,009 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
Submitted Solution:
```
n=int(input())
x=[0 for i in range(10)]
while True:
if n==0:
break
for i in range(n):
a=int(input())
x[a]+=1
for i in range(10):
if x[i]==0:
print('{}'.format('-'))
else:
print('{}'.format(x[i]*'*'))
```
No
| 96,010 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
Submitted Solution:
```
n=int(input())
x=[0 for i in range(10)]
while True:
if n==0:
break
for i in range(n):
a=int(input())
if a==0:
x[0]+=1
elif a==1:
x[1]+=1
elif a==2:
x[2]+=1
elif a==3:
x[3]+=1
elif a==4:
x[4]+=1
elif a==5:
x[5]+=1
elif a==6:
x[6]+=1
elif a==7:
x[7]+=1
elif a==8:
x[8]+=1
else:
x[9]+=1
for i in range(10):
if x[i]==0:
print('{}'.format('-'))
else:
print('{}'.format(x[i]*'*'))
```
No
| 96,011 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
Submitted Solution:
```
while True:
n = int(input())
if n == 0:
break
d = {k: 0 for k in range(n)}
for _ in range(n):
x = int(input())
d[x] += 1
for k in range(n):
print("*"*d[k] + "-"*(d[k]==0))
```
No
| 96,012 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.
Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
c1
c2
::
cn
The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).
The number of datasets does not exceed 20.
Output
For each input dataset, the number of sales is output in numerical order of each ice cream type.
Example
Input
15
2
6
7
0
1
9
8
7
3
8
9
4
8
2
2
3
9
1
5
0
Output
*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*
Submitted Solution:
```
#!/usr/bin/env python3
while True:
n = int(input())
data = [0] * 10
if n == 0:
break
for _ in range(n):
in_data = int(input())
data[in_data - 1] += 1
for d in data:
for _ in range(d):
print("*", end="")
if d == 0:
print("-")
else:
print(end="\n")
```
No
| 96,013 |
Provide a correct Python 3 solution for this coding contest problem.
In the year 30XX, an expedition team reached a planet and found a warp machine suggesting the existence of a mysterious supercivilization. When you go through one of its entrance gates, you can instantaneously move to the exit irrespective of how far away it is. You can move even to the end of the universe at will with this technology!
The scientist team started examining the machine and successfully identified all the planets on which the entrances to the machine were located. Each of these N planets (identified by an index from $1$ to $N$) has an entrance to, and an exit from the warp machine. Each of the entrances and exits has a letter inscribed on it.
The mechanism of spatial mobility through the warp machine is as follows:
* If you go into an entrance gate labeled with c, then you can exit from any gate with label c.
* If you go into an entrance located on the $i$-th planet, then you can exit from any gate located on the $j$-th planet where $i < j$.
Once you have reached an exit of the warp machine on a planet, you can continue your journey by entering into the warp machine on the same planet. In this way, you can reach a faraway planet. Our human race has decided to dispatch an expedition to the star $N$, starting from Star $1$ and using the warp machine until it reaches Star $N$. To evaluate the possibility of successfully reaching the destination. it is highly desirable for us to know how many different routes are available for the expedition team to track.
Given information regarding the stars, make a program to enumerate the passages from Star $1$ to Star $N$.
Input
The input is given in the following format.
$N$
$s$
$t$
The first line provides the number of the stars on which the warp machine is located $N$ ($2 \leq N \leq 100,000$). The second line provides a string $s$ of length $N$, each component of which represents the letter inscribed on the entrance of the machine on the star. By the same token, the third line provides a string $t$ of length $N$ consisting of the letters inscribed on the exit of the machine. Two strings $s$ and $t$ consist all of lower-case alphabetical letters, and the $i$-th letter of these strings corresponds respectively to the entrance and exit of Star $i$ machine.
Output
Divide the number of possible routes from Star $1$ to Star $N$ obtained above by 1,000,000,007, and output the remainder.
Examples
Input
6
abbaba
baabab
Output
5
Input
25
neihsokcpuziafoytisrevinu
universityofaizupckoshien
Output
4
"Correct Solution:
```
N = int(input())
s = input()
t = input()
D = {t[-1]: 1}
for i in range(N-2, 0, -1):
si = s[i]; ti = t[i]
v = D.get(si, 0)
D[ti] = (D.get(ti, 0) + v) % (10**9+7)
print(D.get(s[0], 0))
```
| 96,014 |
Provide a correct Python 3 solution for this coding contest problem.
In the year 30XX, an expedition team reached a planet and found a warp machine suggesting the existence of a mysterious supercivilization. When you go through one of its entrance gates, you can instantaneously move to the exit irrespective of how far away it is. You can move even to the end of the universe at will with this technology!
The scientist team started examining the machine and successfully identified all the planets on which the entrances to the machine were located. Each of these N planets (identified by an index from $1$ to $N$) has an entrance to, and an exit from the warp machine. Each of the entrances and exits has a letter inscribed on it.
The mechanism of spatial mobility through the warp machine is as follows:
* If you go into an entrance gate labeled with c, then you can exit from any gate with label c.
* If you go into an entrance located on the $i$-th planet, then you can exit from any gate located on the $j$-th planet where $i < j$.
Once you have reached an exit of the warp machine on a planet, you can continue your journey by entering into the warp machine on the same planet. In this way, you can reach a faraway planet. Our human race has decided to dispatch an expedition to the star $N$, starting from Star $1$ and using the warp machine until it reaches Star $N$. To evaluate the possibility of successfully reaching the destination. it is highly desirable for us to know how many different routes are available for the expedition team to track.
Given information regarding the stars, make a program to enumerate the passages from Star $1$ to Star $N$.
Input
The input is given in the following format.
$N$
$s$
$t$
The first line provides the number of the stars on which the warp machine is located $N$ ($2 \leq N \leq 100,000$). The second line provides a string $s$ of length $N$, each component of which represents the letter inscribed on the entrance of the machine on the star. By the same token, the third line provides a string $t$ of length $N$ consisting of the letters inscribed on the exit of the machine. Two strings $s$ and $t$ consist all of lower-case alphabetical letters, and the $i$-th letter of these strings corresponds respectively to the entrance and exit of Star $i$ machine.
Output
Divide the number of possible routes from Star $1$ to Star $N$ obtained above by 1,000,000,007, and output the remainder.
Examples
Input
6
abbaba
baabab
Output
5
Input
25
neihsokcpuziafoytisrevinu
universityofaizupckoshien
Output
4
"Correct Solution:
```
from collections import defaultdict
MOD = 1000000007
n = int(input())
s = input()
t = input()
dic = defaultdict(int)
dic[s[0]] = 1
for cs, ct in zip(s[1:n-1], t[1:n-1]):
dic[cs] += dic[ct]
dic[cs] %= MOD
print(dic[t[-1]])
```
| 96,015 |
Provide a correct Python 3 solution for this coding contest problem.
An bydrocarbon is an organic compound which contains only carbons and hydrogens. An isomer is a compound that has the same number of carbons but different structures. Heptane, for example, is a hydrocarbon with 7 carbons. It has nine isomers. The structural formula of three are shown in Figure 1. Carbons are represented by the letter C, and bonds between carbons are represented by a straight line. In all figures, hydrogens are not represented for simplicity. Each carbon can be connected to a maximum of 4 carbons.
<image>
---
Figure 1: These three examples of isomers of heptane have the same number of carbons but different structures.
---
Let define a chain in an isomer as a sequence of connected carbons without branches. An isomer can have many chains of the same length. Figure 2 shows the longest chain of carbons for each of the represented isomer. Note that there can be many instances of longest chain in an isomer.
<image>
---
Figure 2: The figures shows one instance of longest chain of carbons in each isomer. The first and the second isomers show longest chains of 5 carbons. The longest chain in the third isomer has 4 carbons.
---
Your task is to identify the number of carbons of the largest possible carbon compound whose longest carbon chain has n (1 ≤ n ≤ 30) carbons.
Input
Each input contains a list of number of carbons, i.e. the length of a carbon chain.
The number of input lines is less than or equal to 30.
Output
For each number n in input, identify the number of carbons of the largest possible carbon compound whose longest carbon chain has n carbons.
Example
Input
1
4
Output
1
8
"Correct Solution:
```
# AOJ 1011: Finding the Largest Carbon Compound Give...
# Python3 2018.7.4 bal4u
a = [0]*32
a[1], a[2] = 1, 2
for i in range(3, 31): a[i] = 3*a[i-2] + 2
while True:
try: i = int(input())
except: break
print(a[i])
```
| 96,016 |
Provide a correct Python 3 solution for this coding contest problem.
After long studying how embryos of organisms become asymmetric during their development, Dr. Podboq, a famous biologist, has reached his new hypothesis. Dr. Podboq is now preparing a poster for the coming academic conference, which shows a tree representing the development process of an embryo through repeated cell divisions starting from one cell. Your job is to write a program that transforms given trees into forms satisfying some conditions so that it is easier for the audience to get the idea.
A tree representing the process of cell divisions has a form described below.
* The starting cell is represented by a circle placed at the top.
* Each cell either terminates the division activity or divides into two cells. Therefore, from each circle representing a cell, there are either no branch downward, or two branches down to its two child cells.
Below is an example of such a tree.
<image>
Figure F-1: A tree representing a process of cell divisions
According to Dr. Podboq's hypothesis, we can determine which cells have stronger or weaker asymmetricity by looking at the structure of this tree representation. First, his hypothesis defines "left-right similarity" of cells as follows:
1. The left-right similarity of a cell that did not divide further is 0.
2. For a cell that did divide further, we collect the partial trees starting from its child or descendant cells, and count how many kinds of structures they have. Then, the left-right similarity of the cell is defined to be the ratio of the number of structures that appear both in the right child side and the left child side. We regard two trees have the same structure if we can make them have exactly the same shape by interchanging two child cells of arbitrary cells.
For example, suppose we have a tree shown below:
<image>
Figure F-2: An example tree
The left-right similarity of the cell A is computed as follows. First, within the descendants of the cell B, which is the left child cell of A, the following three kinds of structures appear. Notice that the rightmost structure appears three times, but when we count the number of structures, we count it only once.
<image>
Figure F-3: Structures appearing within the descendants of the cell B
On the other hand, within the descendants of the cell C, which is the right child cell of A, the following four kinds of structures appear.
<image>
Figure F-4: Structures appearing within the descendants of the cell C
Among them, the first, second, and third ones within the B side are regarded as the same structure as the second, third, and fourth ones within the C side, respectively. Therefore, there are four structures in total, and three among them are common to the left side and the right side, which means the left-right similarity of A is 3/4.
Given the left-right similarity of each cell, Dr. Podboq's hypothesis says we can determine which of the cells X and Y has stronger asymmetricity by the following rules.
1. If X and Y have different left-right similarities, the one with lower left-right similarity has stronger asymmetricity.
2. Otherwise, if neither X nor Y has child cells, they have completely equal asymmetricity.
3. Otherwise, both X and Y must have two child cells. In this case, we compare the child cell of X with stronger (or equal) asymmetricity (than the other child cell of X) and the child cell of Y with stronger (or equal) asymmetricity (than the other child cell of Y), and the one having a child with stronger asymmetricity has stronger asymmetricity.
4. If we still have a tie, we compare the other child cells of X and Y with weaker (or equal) asymmetricity, and the one having a child with stronger asymmetricity has stronger asymmetricity.
5. If we still have a tie again, X and Y have completely equal asymmetricity.
When we compare child cells in some rules above, we recursively apply this rule set.
Now, your job is to write a program that transforms a given tree representing a process of cell divisions, by interchanging two child cells of arbitrary cells, into a tree where the following conditions are satisfied.
1. For every cell X which is the starting cell of the given tree or a left child cell of some parent cell, if X has two child cells, the one at left has stronger (or equal) asymmetricity than the one at right.
2. For every cell X which is a right child cell of some parent cell, if X has two child cells, the one at right has stronger (or equal) asymmetricity than the one at left.
In case two child cells have equal asymmetricity, their order is arbitrary because either order would results in trees of the same shape.
For example, suppose we are given the tree in Figure F-2. First we compare B and C, and because B has lower left-right similarity, which means stronger asymmetricity, we keep B at left and C at right. Next, because B is the left child cell of A, we compare two child cells of B, and the one with stronger asymmetricity is positioned at left. On the other hand, because C is the right child cell of A, we compare two child cells of C, and the one with stronger asymmetricity is positioned at right. We examine the other cells in the same way, and the tree is finally transformed into the tree shown below.
<image>
Figure F-5: The example tree after the transformation
Please be warned that the only operation allowed in the transformation of a tree is to interchange two child cells of some parent cell. For example, you are not allowed to transform the tree in Figure F-2 into the tree below.
<image>
Figure F-6: An example of disallowed transformation
Input
The input consists of n lines (1≤n≤100) describing n trees followed by a line only containing a single zero which represents the end of the input. Each tree includes at least 1 and at most 127 cells. Below is an example of a tree description.
> `((x (x x)) x)`
This description represents the tree shown in Figure F-1. More formally, the description of a tree is in either of the following two formats.
> "`(`" <description of a tree starting at the left child> <single space> <description of a tree starting at the right child> ")"
or
> "`x`"
The former is the description of a tree whose starting cell has two child cells, and the latter is the description of a tree whose starting cell has no child cell.
Output
For each tree given in the input, print a line describing the result of the tree transformation. In the output, trees should be described in the same formats as the input, and the tree descriptions must appear in the same order as the input. Each line should have no extra character other than one tree description.
Sample Input
(((x x) x) ((x x) (x (x x))))
(((x x) (x x)) ((x x) ((x x) (x x))))
(((x x) ((x x) x)) (((x (x x)) x) (x x)))
(((x x) x) ((x x) (((((x x) x) x) x) x)))
(((x x) x) ((x (x x)) (x (x x))))
((((x (x x)) x) (x ((x x) x))) ((x (x x)) (x x)))
((((x x) x) ((x x) (x (x x)))) (((x x) (x x)) ((x x) ((x x) (x x)))))
0
Output for the Sample Input
((x (x x)) ((x x) ((x x) x)))
(((x x) ((x x) (x x))) ((x x) (x x)))
(((x ((x x) x)) (x x)) ((x x) ((x x) x)))
(((x ((x ((x x) x)) x)) (x x)) ((x x) x))
((x (x x)) ((x (x x)) ((x x) x)))
(((x (x x)) (x x)) ((x ((x x) x)) ((x (x x)) x)))
(((x (x x)) ((x x) ((x x) x))) (((x x) (x x)) (((x x) (x x)) (x x))))
Example
Input
(((x x) x) ((x x) (x (x x))))
(((x x) (x x)) ((x x) ((x x) (x x))))
(((x x) ((x x) x)) (((x (x x)) x) (x x)))
(((x x) x) ((x x) (((((x x) x) x) x) x)))
(((x x) x) ((x (x x)) (x (x x))))
((((x (x x)) x) (x ((x x) x))) ((x (x x)) (x x)))
((((x x) x) ((x x) (x (x x)))) (((x x) (x x)) ((x x) ((x x) (x x)))))
0
Output
((x (x x)) ((x x) ((x x) x)))
(((x x) ((x x) (x x))) ((x x) (x x)))
(((x ((x x) x)) (x x)) ((x x) ((x x) x)))
(((x ((x ((x x) x)) x)) (x x)) ((x x) x))
((x (x x)) ((x (x x)) ((x x) x)))
(((x (x x)) (x x)) ((x ((x x) x)) ((x (x x)) x)))
(((x (x x)) ((x x) ((x x) x))) (((x x) (x x)) (((x x) (x x)) (x x))))
"Correct Solution:
```
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def parse(S):
S = S + "$"
cur = 0
mp = {"01": 0}
sp = {"01": {0}}
sv = {"01": (0, 1)}
lbl = 1
fmt = "0{}{}1".format
def comp(left, right):
lcs, lb = left
rcs, rb = right
a0, b0 = sv[lb]
a1, b1 = sv[rb]
if a1*b0 != a0*b1:
return a1*b0 - a0*b1
if lcs is None and rcs is None:
return 0
ll, lr = lcs
rl, rr = rcs
cl = comp(ll, rl)
if cl != 0:
return cl
cr = comp(lr, rr)
if cr != 0:
return cr
return 0
def expr():
nonlocal cur, lbl
if S[cur] == "x":
cur += 1 # "x"
return (None, "01")
cur += 1 # "("
left = expr()
cur += 1 # " "
right = expr()
cur += 1 # ")"
lb = left[1]; rb = right[1]
eb = fmt(lb, rb) if lb < rb else fmt(rb, lb)
if eb not in mp:
mp[eb] = lbl
sp[eb] = sp[lb] | sp[rb] | {lbl}
sv[eb] = (len(sp[lb] & sp[rb]), len(sp[lb] | sp[rb]))
lbl += 1
if comp(left, right) < 0:
left, right = right, left
return ((left, right), eb)
return expr()
def dfs(root, m):
if root[0] is None:
return "x"
left, right = root[0]
if m == 0:
return "({} {})".format(dfs(left, 0), dfs(right, 1))
return "({} {})".format(dfs(right, 0), dfs(left, 1))
def solve():
S = readline().strip()
if S == "0":
return False
res = parse(S)
write(dfs(res, 0))
write("\n")
return True
while solve():
...
```
| 96,017 |
Provide a correct Python 3 solution for this coding contest problem.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
"Correct Solution:
```
# coding: utf-8
while 1:
n=int(input())
if n==0:
break
dic={}
ok=[[False for i in range(30)] for i in range(n)]
for i in range(n):
dic[i]=[i]
for m in list(map(int,input().split()))[1:]:
ok[i][m-1]=True
f=False
for i in range(30):
tmp=[]
for j in range(n):
if ok[j][i]:
tmp+=list(dic[j])
tmp=set(tmp)
for j in range(n):
if ok[j][i]:
dic[j]=list(tmp)
if len(dic[j])==n:
print(i+1)
f=True
break
if f:
break
if not f:
print(-1)
```
| 96,018 |
Provide a correct Python 3 solution for this coding contest problem.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
"Correct Solution:
```
import itertools
while True:
N = int(input())
if not N:
break
D = [[] for _ in range(30)]
for i in range(N):
for x in map(int, input().split()[1:]):
D[x - 1].append(i)
C = [1 << i for i in range(N)]
for d in range(30):
for i, j in itertools.combinations(D[d], 2):
C[i] = C[j] = C[i] | C[j]
if any(x == (1 << N) - 1 for x in C):
print(d + 1)
break
else:
print(-1)
```
| 96,019 |
Provide a correct Python 3 solution for this coding contest problem.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
"Correct Solution:
```
import heapq
while True:
N = int(input())
if not N:
break
f = [0] * N
for i in range(N):
f[i] = list(map(int,input().split()[1:]))
dp = [ [0] * 51 for i in range(51) ]
for i in range(N):
for j in range(N):
dp[j][i] = 1<<i
for i in range(1,31):
ds = [ j for j in range(N) if i in f[j]]
for d1 in ds:
for d2 in ds:
dp[i][d1] |= dp[i-1][d2]
for j in range(N):
dp[i][j] |= dp[i-1][j]
ans = 40
for i in range(31):
for j in range(N):
if dp[i][j] == (1<<N)-1:
ans = min( (ans,i) )
if ans > 30:
print(-1)
else:
print(ans)
```
| 96,020 |
Provide a correct Python 3 solution for this coding contest problem.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
"Correct Solution:
```
import sys
from collections import deque,defaultdict
def bfs(s):
bfs_map = defaultdict(lambda : 1)
bfs_map[s] = 0
q = deque([s])
b = defaultdict(lambda : 0)
b[s[0]] = 1
while q:
x = q.popleft()
for y in v[x]:
if bfs_map[y]:
bfs_map[y] = 0
q.append(y)
b[y[0]] = 1
for i in range(n):
if not b[i]:
return 0
return 1
while 1:
n = int(sys.stdin.readline())
if n == 0:
break
T = [[] for i in range(30)]
v = defaultdict(list)
for i in range(n):
s = list(map(int, sys.stdin.readline()[:-1].split()))
t = s[1:]
t.sort()
for j in t:
T[j-1].append(i)
for j in range(1,s[0]):
v[(i,t[j]-1)].append((i,t[j-1]-1))
f = 1
for t in range(30):
for i in range(len(T[t])-1):
x = T[t][i]
y = T[t][i+1]
v[(x,t)].append((y,t))
v[(y,t)].append((x,t))
for t in range(30):
if T[t]:
if bfs((T[t][0],t)):
f = 0
print(t+1)
break
if not f:
break
if f:
print(-1)
```
| 96,021 |
Provide a correct Python 3 solution for this coding contest problem.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
"Correct Solution:
```
MAX_N = 50
MAX_DAY = 30
def solve(n, f):
dp = [[set() for j in range(n)] for i in range(MAX_DAY + 1)]
for i in range(n):
dp[0][i].add(i)
for d in range(1, MAX_DAY + 1):
# for line in dp[:5]:
# print(line)
for i in range(n):
dp[d][i] |= dp[d - 1][i]
for j in range(n):
if f[d][i] and f[d][j]:
dp[d][i] |= dp[d - 1][j]
if len(dp[d][i]) == n:
return d
return -1
######################################
while True:
n = int(input())
if n == 0:
exit()
f = [[False] * n for i in range(MAX_DAY + 1)]
for i in range(n):
_, *li = map(int, input().split())
for x in li:
f[x][i] = True
# for line in f:
# print(line)
print(solve(n, f))
```
| 96,022 |
Provide a correct Python 3 solution for this coding contest problem.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
"Correct Solution:
```
def solve(n, meetables):
mets = [set() for _ in range(n)]
for d, meetable in enumerate(meetables[1:]):
today = meetable.copy()
for i in meetable:
today.update(mets[i])
mets[i] = today
if len(today) == n:
return d + 1
return -1
while True:
n = int(input())
if not n:
break
meetables = [set() for _ in range(31)]
for i in range(n):
for d in map(int, input().split()[1:]):
meetables[d].add(i)
print(solve(n, meetables))
```
| 96,023 |
Provide a correct Python 3 solution for this coding contest problem.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
"Correct Solution:
```
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(input())
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())
def c(n,d):
return n+d*N
def dfs(s,n):
global visited
visited[s][n] = True
for t in lines[s]:
if not visited[t][n]:
dfs(t,n)
while True:
N = inp()
if N == 0:
break
else:
days = 30
nds = [[False]*days for _ in range(N)]
for n in range(N):
tmpl = inpl()
for i in range(1,tmpl[0]+1):
nds[n][tmpl[i]-1] = True
lines = defaultdict(set)
cnt = 0
for n in range(N):
for d1 in range(days):
for d2 in range(d1,days):
if nds[n][d1] and nds[n][d2]:
lines[c(n,d1)].add(c(n,d2))
for d in range(days):
for n1 in range(N):
for n2 in range(n1,N):
if nds[n1][d] and nds[n2][d]:
lines[c(n1,d)].add(c(n2,d))
lines[c(n2,d)].add(c(n1,d))
visited = [[False]*N for _ in range(c(N,days))]
for n in range(N):
for d in range(days):
if nds[n][d]:
dfs(c(n,d),n)
#print(visited)
for b in range(N*days):
for n in range(N):
#print(b,n,visited[b][n])
if visited[b][n]:
continue
else:
break
else:
print(b//N+1)
break
else:
print(-1)
```
| 96,024 |
Provide a correct Python 3 solution for this coding contest problem.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
"Correct Solution:
```
MAX_N = 50
MAX_DAY = 30
def solve(n, f):
dp = [{i} for i in range(n)]
for d in range(1, MAX_DAY + 1):
for i in range(n):
for j in range(n):
if f[d][i] and f[d][j]:
dp[i] |= dp[j]
if len(dp[i]) == n:
return d
return -1
######################################
while True:
n = int(input())
if n == 0:
exit()
f = [[False] * n for i in range(MAX_DAY + 1)]
for i in range(n):
_, *li = map(int, input().split())
for x in li:
f[x][i] = True
print(solve(n, f))
```
| 96,025 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
Submitted Solution:
```
while True:
N = int(input())
if not N:
break
D = [[] for _ in range(30)]
for i in range(N):
for x in map(int, input().split()[1:]):
D[x - 1].append(i)
C = [1 << i for i in range(N)]
for d in range(30):
for i in D[d]:
for j in D[d]:
C[i] = C[i] | C[j]
if any(x == (1 << N) - 1 for x in C):
print(d + 1)
break
else:
print(-1)
```
Yes
| 96,026 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
Submitted Solution:
```
import itertools
while True:
N = int(input())
if not N:
break
D = [[] for _ in range(30)]
for i in range(N):
for x in map(int, input().split()[1:]):
D[x - 1].append(i)
C = [1 << i for i in range(N)]
for d in range(30):
for i, j in itertools.permutations(D[d], 2):
C[i] = C[i] | C[j]
if any(x == (1 << N) - 1 for x in C):
print(d + 1)
break
else:
print(-1)
```
Yes
| 96,027 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
while True:
n = I()
if n == 0:
break
a = [LI()[1:] for _ in range(n)]
d = collections.defaultdict(list)
for i in range(n):
for c in a[i]:
d[c].append(i)
r = -1
s = [set([i]) for i in range(n)]
for k in sorted(list(d.keys())):
ts = set()
for c in d[k]:
ts |= s[c]
if len(ts) == n:
r = k
break
for c in d[k]:
s[c] |= ts
rr.append(r)
return '\n'.join(map(str,rr))
print(main())
```
Yes
| 96,028 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
Submitted Solution:
```
def solve():
from sys import stdin
f_i = stdin
ans = []
while True:
n = int(f_i.readline())
if n == 0:
break
last_day = 1
schedule = [set() for i in range(31)]
for i in range(n):
line = map(int, f_i.readline().split())
f = next(line)
for day in line:
schedule[day].add(i)
if day > last_day:
last_day = day
groups = [set() for i in range(n)]
for day in range(1, last_day + 1):
member1 = schedule[day]
member2 = member1.copy()
for person in member1:
member2 |= groups[person]
if len(member2) == n:
ans.append(day)
break
for person in member1:
groups[person] |= member2
else:
ans.append(-1)
print('\n'.join(map(str, ans)))
solve()
```
Yes
| 96,029 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
Submitted Solution:
```
while(True):
n = int(input())
if n == 0:
break
d = []
for i in range(n):
ll = input().split()
l = [int(_) for _ in ll]
f = l[0]
tmp = []
for j in range(1, f+1):
tmp.append(l[j])
d += [tmp]
mp = [[0 for i in range(31)] for j in range(n)]
for member in range(n):
for day in d[member]:
mp[member][day] = 1
clr = [0 for i in range(n)]
ans = [1 for i in range(n)]
flg = 0
for day in range(31):
tmp = []
s = 0
for member in range(n):
s += mp[member][day]
if mp[member][day] == 1:
tmp.append(member)
if s > 1:
for member in tmp:
clr[member] = 1
if clr == ans and flg == 0:
print(day)
flg = 1
if flg == 0:
print(-1)
```
No
| 96,030 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
Submitted Solution:
```
from itertools import combinations
from decimal import Decimal
def get_point(line1, line2):
m1, k1 = line1
m2, k2 = line2
if m1 == m2:
return None
elif m1 is None and m2 is None:
return None
elif m1 is None:
x = k1
y = m2 * x + k2
elif m2 is None:
x = k2
y = m1 * x + k1
else:
x = (k2-k1)/(m2-m1)
y = m1*x+k
if -100 < x < 100 and -100 < y < 100:
return (x, y)
else:
return None
while True:
N = int(input())
if not N:
break
lines = []
for i in range(N):
x1, y1, x2, y2 = [Decimal(int(i)) for i in input().split()]
if x1 == x2:
lines.append(None, x1)
else:
m = (y2-y1) / (x2-x1)
k = y1 - m * x1
lines.append((m, k))
iterated_lines = []
ans = 1
for line1 in lines:
pt_set = set()
for line2 in iterated_lines:
pt = get_point(line1, line2)
# print(pt)
if pt:
pt_set.add(pt)
ans += len(pt_set) + 1
iterated_lines.append(line1)
print(ans)
```
No
| 96,031 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
Submitted Solution:
```
while(True):
n = int(input())
if n == 0:
break
d = []
for i in range(n):
ll = input().split()
l = [int(_) for _ in ll]
f = l[0]
tmp = []
for j in range(1, f+1):
tmp.append(l[j])
d += [tmp]
mp = [[0 for i in range(30)] for j in range(n)]
for member in range(n):
for day in d[member]:
mp[member][day] = 1
clr = [0 for i in range(n)]
ans = [1 for i in range(n)]
flg = 0
for day in range(30):
tmp = []
s = 0
for member in range(n):
s += mp[member][day]
if mp[member][day] == 1:
tmp.append(member)
if s > 1:
for member in tmp:
clr[member] = 1
if clr == ans and flg == 0:
print(day)
flg = 1
if flg == 0:
print(-1)
```
No
| 96,032 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.
Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.
Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.
By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.
Input
The input consists of multiple datasets.
Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.
There is one line containing only 0 at the end of the input.
Output
Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.
Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.
Example
Input
4
1 1
2 2 3
2 1 2
3 3 4 5
0
Output
3
Submitted Solution:
```
import heapq
while True:
N = int(input())
if not N:
break
f = [0] * N
for i in range(N):
f[i] = list(map(int,input().split()[1:]))
dp = [ [0] * 51 for i in range(51) ]
for i in range(N):
for j in range(N):
dp[j][i] = 1<<i
for i in range(1,31):
ds = [ j for j in range(N) if i in f[j]]
for d1 in ds:
for d2 in ds:
dp[i][d1] |= dp[i-1][d2]
ans = 40
for i in range(31):
for j in range(N):
if dp[i][j] == (1<<N)-1:
ans = min( (ans,i) )
if ans > 30:
print(-1)
else:
print(ans)
```
No
| 96,033 |
Provide a correct Python 3 solution for this coding contest problem.
A dial lock is a kind of lock which has some dials with printed numbers. It has a special sequence of numbers, namely an unlocking sequence, to be opened.
You are working at a manufacturer of dial locks. Your job is to verify that every manufactured lock is unlocked by its unlocking sequence. In other words, you have to rotate many dials of many many locks.
It’s a very hard and boring task. You want to reduce time to open the locks. It’s a good idea to rotate multiple dials at one time. It is, however, a difficult problem to find steps to open a given lock with the fewest rotations. So you decided to write a program to find such steps for given initial and unlocking sequences.
Your company’s dial locks are composed of vertically stacked k (1 ≤ k ≤ 10) cylindrical dials. Every dial has 10 numbers, from 0 to 9, along the side of the cylindrical shape from the left to the right in sequence. The neighbor on the right of 9 is 0.
A dial points one number at a certain position. If you rotate a dial to the left by i digits, the dial newly points the i-th right number. In contrast, if you rotate a dial to the right by i digits, it points the i-th left number. For example, if you rotate a dial pointing 8 to the left by 3 digits, the dial newly points 1.
You can rotate more than one adjacent dial at one time. For example, consider a lock with 5 dials. You can rotate just the 2nd dial. You can rotate the 3rd, 4th and 5th dials at the same time. But you cannot rotate the 1st and 3rd dials at one time without rotating the 2nd dial. When you rotate multiple dials, you have to rotate them to the same direction by the same digits.
Your program is to calculate the fewest number of rotations to unlock, for given initial and unlocking sequences. Rotating one or more adjacent dials to the same direction by the same digits is counted as one rotation.
Input
The input consists of multiple datasets. Each datset consists of two lines. The first line contains an integer k. The second lines contain two strings, separated by a space, which indicate the initial and unlocking sequences.
The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed.
Output
For each dataset, print the minimum number of rotations in one line.
Example
Input
4
1357 4680
6
777777 003330
0
Output
1
2
"Correct Solution:
```
def solve():
def bfs(k):
start, goal = file_input.readline().split()
if start == goal:
return 0
start = map(int, start)
goal = map(int, goal)
diff = [(g - s) % 10 for g, s in zip(goal, start)]
q = [diff]
checked = {tuple(diff): True}
ans = 0
while q:
ans += 1
t_q = []
for d in q:
for i, r in enumerate(d):
if r != 0:
break
for j in range(i, k):
d[j] -= r
d[j] %= 10
key = tuple(d)
if key in checked:
continue
if sum(d) == 0:
return ans
checked[key] = True
t_q.append(d[:])
q = t_q
from sys import stdin
file_input = stdin
while True:
k = int(file_input.readline())
if k == 0:
break
print(bfs(k))
solve()
```
| 96,034 |
Provide a correct Python 3 solution for this coding contest problem.
A dial lock is a kind of lock which has some dials with printed numbers. It has a special sequence of numbers, namely an unlocking sequence, to be opened.
You are working at a manufacturer of dial locks. Your job is to verify that every manufactured lock is unlocked by its unlocking sequence. In other words, you have to rotate many dials of many many locks.
It’s a very hard and boring task. You want to reduce time to open the locks. It’s a good idea to rotate multiple dials at one time. It is, however, a difficult problem to find steps to open a given lock with the fewest rotations. So you decided to write a program to find such steps for given initial and unlocking sequences.
Your company’s dial locks are composed of vertically stacked k (1 ≤ k ≤ 10) cylindrical dials. Every dial has 10 numbers, from 0 to 9, along the side of the cylindrical shape from the left to the right in sequence. The neighbor on the right of 9 is 0.
A dial points one number at a certain position. If you rotate a dial to the left by i digits, the dial newly points the i-th right number. In contrast, if you rotate a dial to the right by i digits, it points the i-th left number. For example, if you rotate a dial pointing 8 to the left by 3 digits, the dial newly points 1.
You can rotate more than one adjacent dial at one time. For example, consider a lock with 5 dials. You can rotate just the 2nd dial. You can rotate the 3rd, 4th and 5th dials at the same time. But you cannot rotate the 1st and 3rd dials at one time without rotating the 2nd dial. When you rotate multiple dials, you have to rotate them to the same direction by the same digits.
Your program is to calculate the fewest number of rotations to unlock, for given initial and unlocking sequences. Rotating one or more adjacent dials to the same direction by the same digits is counted as one rotation.
Input
The input consists of multiple datasets. Each datset consists of two lines. The first line contains an integer k. The second lines contain two strings, separated by a space, which indicate the initial and unlocking sequences.
The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed.
Output
For each dataset, print the minimum number of rotations in one line.
Example
Input
4
1357 4680
6
777777 003330
0
Output
1
2
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
def f(n):
a,b = LS()
if a == b:
return 0
a = [int(c) for c in a]
b = [int(c) for c in b]
aa = [a]
ad = set()
ad.add(tuple(a))
r = 0
while True:
r += 1
na = []
for a in aa:
ti = 0
for i in range(r-1,n):
if a[i] != b[i]:
ti = i
break
sa = b[ti] - a[ti]
for j in range(ti+1, n+1):
t = [(a[i] + sa) % 10 if ti <= i < j else a[i] for i in range(n)]
k = tuple(t)
if k in ad:
continue
if t == b:
return r
ad.add(k)
na.append(t)
aa = na
while True:
n = I()
if n == 0:
break
rr.append(f(n))
return '\n'.join(map(str,rr))
print(main())
```
| 96,035 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A dial lock is a kind of lock which has some dials with printed numbers. It has a special sequence of numbers, namely an unlocking sequence, to be opened.
You are working at a manufacturer of dial locks. Your job is to verify that every manufactured lock is unlocked by its unlocking sequence. In other words, you have to rotate many dials of many many locks.
It’s a very hard and boring task. You want to reduce time to open the locks. It’s a good idea to rotate multiple dials at one time. It is, however, a difficult problem to find steps to open a given lock with the fewest rotations. So you decided to write a program to find such steps for given initial and unlocking sequences.
Your company’s dial locks are composed of vertically stacked k (1 ≤ k ≤ 10) cylindrical dials. Every dial has 10 numbers, from 0 to 9, along the side of the cylindrical shape from the left to the right in sequence. The neighbor on the right of 9 is 0.
A dial points one number at a certain position. If you rotate a dial to the left by i digits, the dial newly points the i-th right number. In contrast, if you rotate a dial to the right by i digits, it points the i-th left number. For example, if you rotate a dial pointing 8 to the left by 3 digits, the dial newly points 1.
You can rotate more than one adjacent dial at one time. For example, consider a lock with 5 dials. You can rotate just the 2nd dial. You can rotate the 3rd, 4th and 5th dials at the same time. But you cannot rotate the 1st and 3rd dials at one time without rotating the 2nd dial. When you rotate multiple dials, you have to rotate them to the same direction by the same digits.
Your program is to calculate the fewest number of rotations to unlock, for given initial and unlocking sequences. Rotating one or more adjacent dials to the same direction by the same digits is counted as one rotation.
Input
The input consists of multiple datasets. Each datset consists of two lines. The first line contains an integer k. The second lines contain two strings, separated by a space, which indicate the initial and unlocking sequences.
The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed.
Output
For each dataset, print the minimum number of rotations in one line.
Example
Input
4
1357 4680
6
777777 003330
0
Output
1
2
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
def f(n):
a,b = LS()
a = [int(c) for c in a]
b = [int(c) for c in b]
aa = [a]
ad = set()
ad.add(tuple(a))
r = 0
while True:
r += 1
na = []
for a in aa:
ti = 0
for i in range(r-1,n):
if a[i] != b[i]:
ti = i
break
sa = b[ti] - a[ti]
for j in range(ti+1, n+1):
t = [(a[i] + sa) % 10 if ti <= i < j else a[i] for i in range(n)]
k = tuple(t)
if k in ad:
continue
if t == b:
return r
ad.add(k)
na.append(t)
aa = na
while True:
n = I()
if n == 0:
break
rr.append(f(n))
return '\n'.join(map(str,rr))
print(main())
```
No
| 96,036 |
Provide a correct Python 3 solution for this coding contest problem.
The trafic on the Internet is increasing these days due to smartphones. The wireless carriers have to enhance their network infrastructure.
The network of a wireless carrier consists of a number of base stations and lines. Each line connects two base stations bi-directionally. The bandwidth of a line increases every year and is given by a polynomial f(x) of the year x.
Your task is, given the network structure, to write a program to calculate the maximal bandwidth between the 1-st and N-th base stations as a polynomial of x.
Input
The input consists of multiple datasets. Each dataset has the following format:
N M
u1 v1 p1
...
uM vM pM
The first line of each dataset contains two integers N (2 ≤ N ≤ 50) and M (0 ≤ M ≤ 500), which indicates the number of base stations and lines respectively. The following M lines describe the network structure. The i-th of them corresponds to the i-th network line and contains two integers ui and vi and a polynomial pi. ui and vi indicate the indices of base stations (1 ≤ ui, vi ≤ N); pi indicates the network bandwidth.
Each polynomial has the form of:
aLxL + aL-1xL-1 + ... + a2x2 + a1x + a0
where L (0 ≤ L ≤ 50) is the degree and ai's (0 ≤ i ≤ L, 0 ≤ ai ≤ 100) are the coefficients. In the input,
* each term aixi (for i ≥ 2) is represented as <ai>x^<i>
* the linear term (a1x) is represented as <a1>x;
* the constant (a0) is represented just by digits;
* these terms are given in the strictly decreasing order of the degrees and connected by a plus sign ("+");
* just like the standard notations, the <ai> is omitted if ai = 1 for non-constant terms;
* similarly, the entire term is omitted if ai = 0 for any terms; and
* the polynomial representations contain no space or characters other than digits, "x", "^", and "+".
For example, 2x2 + 3x + 5 is represented as 2x^2+3x+5; 2x3 + x is represented as 2x^3+x, not 2x^3+0x^2+1x+0 or the like. No polynomial is a constant zero, i.e. the one with all the coefficients being zero.
The end of input is indicated by a line with two zeros. This line is not part of any dataset.
Output
For each dataset, print the maximal bandwidth as a polynomial of x. The polynomial should be represented in the same way as the input format except that a constant zero is possible and should be represented by "0" (without quotes).
Example
Input
3 3
1 2 x+2
2 3 2x+1
3 1 x+1
2 0
3 2
1 2 x
2 3 2
4 3
1 2 x^3+2x^2+3x+4
2 3 x^2+2x+3
3 4 x+2
0 0
Output
2x+3
0
2
x+2
"Correct Solution:
```
import collections
class MyList(list):
def __init__(self, x=[]):
list.__init__(self, x)
def __iadd__(self, A):
ret = MyList()
for a, b in zip(self, A):
ret.append(a + b)
return ret
def __isub__(self, A):
ret = MyList()
for a, b in zip(self, A):
ret.append(a - b)
return ret
def __gt__(self, A):
for a, b in zip(self, A):
if a != b:
return a > b
return False
class MaxFlow:
"""Dinic Algorithm: find max-flow
complexity: O(EV^2)
used in GRL6A(AOJ)
"""
class Edge:
def __init__(self, to, cap, rev):
self.to, self.cap, self.rev = to, cap, rev
def __init__(self, V, D):
""" V: the number of vertexes
E: adjacency list
source: start point
sink: goal point
"""
self.V = V
self.E = [[] for _ in range(V)]
self.D = D
def zero(self):
return MyList([0] * self.D)
def add_edge(self, fr, to, cap):
self.E[fr].append(self.Edge(to, cap, len(self.E[to])))
self.E[to].append(self.Edge(fr, self.zero(), len(self.E[fr])-1))
def dinic(self, source, sink):
"""find max-flow"""
INF = MyList([10**9] * self.D)
maxflow = self.zero()
while True:
self.bfs(source)
if self.level[sink] < 0:
return maxflow
self.itr = MyList([0] * self.V)
while True:
flow = self.dfs(source, sink, INF)
if flow > self.zero():
maxflow += flow
else:
break
def dfs(self, vertex, sink, flow):
"""find augmenting path"""
if vertex == sink:
return flow
for i in range(self.itr[vertex], len(self.E[vertex])):
self.itr[vertex] = i
e = self.E[vertex][i]
if e.cap > self.zero() and self.level[vertex] < self.level[e.to]:
if flow > e.cap:
d = self.dfs(e.to, sink, e.cap)
else:
d = self.dfs(e.to, sink, flow)
if d > self.zero():
e.cap -= d
self.E[e.to][e.rev].cap += d
return d
return self.zero()
def bfs(self, start):
"""find shortest path from start"""
que = collections.deque()
self.level = [-1] * self.V
que.append(start)
self.level[start] = 0
while que:
fr = que.popleft()
for e in self.E[fr]:
if e.cap > self.zero() and self.level[e.to] < 0:
self.level[e.to] = self.level[fr] + 1
que.append(e.to)
def to_poly(a, l):
if l == 0:
return str(a)
elif l == 1:
return "{}x".format('' if a == 1 else a)
else:
return "{}x^{}".format('' if a == 1 else a, l)
while True:
N, M = map(int, input().split())
if N == M == 0:
break
mf = MaxFlow(N, 51)
for _ in range(M):
u, v, p = input().split()
u, v = int(u)-1, int(v)-1
poly = MyList([0] * 51)
for x in p.split('+'):
try:
num = int(x)
poly[-1] = num
except ValueError:
a, l = x.split('x')
if l:
poly[-int(l.strip("^"))-1] = int(a) if a else 1
else:
poly[-2] = int(a) if a else 1
mf.add_edge(u, v, poly)
mf.add_edge(v, u, poly)
maxflow = mf.dinic(0, N-1)
ans = '+'.join(to_poly(a, l) for a, l in zip(maxflow, reversed(range(51))) if a)
print(ans if ans else 0)
```
| 96,037 |
Provide a correct Python 3 solution for this coding contest problem.
The trafic on the Internet is increasing these days due to smartphones. The wireless carriers have to enhance their network infrastructure.
The network of a wireless carrier consists of a number of base stations and lines. Each line connects two base stations bi-directionally. The bandwidth of a line increases every year and is given by a polynomial f(x) of the year x.
Your task is, given the network structure, to write a program to calculate the maximal bandwidth between the 1-st and N-th base stations as a polynomial of x.
Input
The input consists of multiple datasets. Each dataset has the following format:
N M
u1 v1 p1
...
uM vM pM
The first line of each dataset contains two integers N (2 ≤ N ≤ 50) and M (0 ≤ M ≤ 500), which indicates the number of base stations and lines respectively. The following M lines describe the network structure. The i-th of them corresponds to the i-th network line and contains two integers ui and vi and a polynomial pi. ui and vi indicate the indices of base stations (1 ≤ ui, vi ≤ N); pi indicates the network bandwidth.
Each polynomial has the form of:
aLxL + aL-1xL-1 + ... + a2x2 + a1x + a0
where L (0 ≤ L ≤ 50) is the degree and ai's (0 ≤ i ≤ L, 0 ≤ ai ≤ 100) are the coefficients. In the input,
* each term aixi (for i ≥ 2) is represented as <ai>x^<i>
* the linear term (a1x) is represented as <a1>x;
* the constant (a0) is represented just by digits;
* these terms are given in the strictly decreasing order of the degrees and connected by a plus sign ("+");
* just like the standard notations, the <ai> is omitted if ai = 1 for non-constant terms;
* similarly, the entire term is omitted if ai = 0 for any terms; and
* the polynomial representations contain no space or characters other than digits, "x", "^", and "+".
For example, 2x2 + 3x + 5 is represented as 2x^2+3x+5; 2x3 + x is represented as 2x^3+x, not 2x^3+0x^2+1x+0 or the like. No polynomial is a constant zero, i.e. the one with all the coefficients being zero.
The end of input is indicated by a line with two zeros. This line is not part of any dataset.
Output
For each dataset, print the maximal bandwidth as a polynomial of x. The polynomial should be represented in the same way as the input format except that a constant zero is possible and should be represented by "0" (without quotes).
Example
Input
3 3
1 2 x+2
2 3 2x+1
3 1 x+1
2 0
3 2
1 2 x
2 3 2
4 3
1 2 x^3+2x^2+3x+4
2 3 x^2+2x+3
3 4 x+2
0 0
Output
2x+3
0
2
x+2
"Correct Solution:
```
import collections
class MyList(list):
def __init__(self, x=[]):
list.__init__(self, x)
def __iadd__(self, A):
return MyList([a + b for a, b in zip(self, A)])
def __isub__(self, A):
return MyList([a - b for a, b in zip(self, A)])
def __gt__(self, A):
for a, b in zip(self, A):
if a != b:
return a > b
return False
class MaxFlow:
"""Dinic Algorithm: find max-flow
complexity: O(EV^2)
used in GRL6A(AOJ)
"""
class Edge:
def __init__(self, to, cap, rev):
self.to, self.cap, self.rev = to, cap, rev
def __init__(self, V, D):
""" V: the number of vertexes
E: adjacency list
source: start point
sink: goal point
"""
self.V = V
self.E = [[] for _ in range(V)]
self.D = D
def zero(self):
return MyList([0] * self.D)
def add_edge(self, fr, to, cap):
self.E[fr].append(self.Edge(to, cap, len(self.E[to])))
self.E[to].append(self.Edge(fr, self.zero(), len(self.E[fr])-1))
def dinic(self, source, sink):
"""find max-flow"""
INF = MyList([10**9] * self.D)
maxflow = self.zero()
while True:
self.bfs(source)
if self.level[sink] < 0:
return maxflow
self.itr = MyList([0] * self.V)
while True:
flow = self.dfs(source, sink, INF)
if flow > self.zero():
maxflow += flow
else:
break
def dfs(self, vertex, sink, flow):
"""find augmenting path"""
if vertex == sink:
return flow
for i in range(self.itr[vertex], len(self.E[vertex])):
self.itr[vertex] = i
e = self.E[vertex][i]
if e.cap > self.zero() and self.level[vertex] < self.level[e.to]:
if flow > e.cap:
d = self.dfs(e.to, sink, e.cap)
else:
d = self.dfs(e.to, sink, flow)
if d > self.zero():
e.cap -= d
self.E[e.to][e.rev].cap += d
return d
return self.zero()
def bfs(self, start):
"""find shortest path from start"""
que = collections.deque()
self.level = [-1] * self.V
que.append(start)
self.level[start] = 0
while que:
fr = que.popleft()
for e in self.E[fr]:
if e.cap > self.zero() and self.level[e.to] < 0:
self.level[e.to] = self.level[fr] + 1
que.append(e.to)
def to_poly(a, l):
if l == 0:
return str(a)
elif l == 1:
return "{}x".format('' if a == 1 else a)
else:
return "{}x^{}".format('' if a == 1 else a, l)
while True:
N, M = map(int, input().split())
if N == M == 0:
break
mf = MaxFlow(N, 51)
for _ in range(M):
u, v, p = input().split()
u, v = int(u)-1, int(v)-1
poly = MyList([0] * 51)
for x in p.split('+'):
try:
num = int(x)
poly[-1] = num
except ValueError:
a, l = x.split('x')
if l:
poly[-int(l.strip("^"))-1] = int(a) if a else 1
else:
poly[-2] = int(a) if a else 1
mf.add_edge(u, v, poly)
mf.add_edge(v, u, poly)
maxflow = mf.dinic(0, N-1)
ans = '+'.join(to_poly(a, l) for a, l in zip(maxflow, reversed(range(51))) if a)
print(ans if ans else 0)
```
| 96,038 |
Provide a correct Python 3 solution for this coding contest problem.
The trafic on the Internet is increasing these days due to smartphones. The wireless carriers have to enhance their network infrastructure.
The network of a wireless carrier consists of a number of base stations and lines. Each line connects two base stations bi-directionally. The bandwidth of a line increases every year and is given by a polynomial f(x) of the year x.
Your task is, given the network structure, to write a program to calculate the maximal bandwidth between the 1-st and N-th base stations as a polynomial of x.
Input
The input consists of multiple datasets. Each dataset has the following format:
N M
u1 v1 p1
...
uM vM pM
The first line of each dataset contains two integers N (2 ≤ N ≤ 50) and M (0 ≤ M ≤ 500), which indicates the number of base stations and lines respectively. The following M lines describe the network structure. The i-th of them corresponds to the i-th network line and contains two integers ui and vi and a polynomial pi. ui and vi indicate the indices of base stations (1 ≤ ui, vi ≤ N); pi indicates the network bandwidth.
Each polynomial has the form of:
aLxL + aL-1xL-1 + ... + a2x2 + a1x + a0
where L (0 ≤ L ≤ 50) is the degree and ai's (0 ≤ i ≤ L, 0 ≤ ai ≤ 100) are the coefficients. In the input,
* each term aixi (for i ≥ 2) is represented as <ai>x^<i>
* the linear term (a1x) is represented as <a1>x;
* the constant (a0) is represented just by digits;
* these terms are given in the strictly decreasing order of the degrees and connected by a plus sign ("+");
* just like the standard notations, the <ai> is omitted if ai = 1 for non-constant terms;
* similarly, the entire term is omitted if ai = 0 for any terms; and
* the polynomial representations contain no space or characters other than digits, "x", "^", and "+".
For example, 2x2 + 3x + 5 is represented as 2x^2+3x+5; 2x3 + x is represented as 2x^3+x, not 2x^3+0x^2+1x+0 or the like. No polynomial is a constant zero, i.e. the one with all the coefficients being zero.
The end of input is indicated by a line with two zeros. This line is not part of any dataset.
Output
For each dataset, print the maximal bandwidth as a polynomial of x. The polynomial should be represented in the same way as the input format except that a constant zero is possible and should be represented by "0" (without quotes).
Example
Input
3 3
1 2 x+2
2 3 2x+1
3 1 x+1
2 0
3 2
1 2 x
2 3 2
4 3
1 2 x^3+2x^2+3x+4
2 3 x^2+2x+3
3 4 x+2
0 0
Output
2x+3
0
2
x+2
"Correct Solution:
```
import collections
def plus_list(A, B):
assert(len(A) == len(B))
return [a + b for a, b in zip(A, B)]
def minus_list(A, B):
assert(len(A) == len(B))
return [a - b for a, b in zip(A, B)]
def gt_list(A, B):
assert(len(A) == len(B))
for a, b in zip(A, B):
if a != b:
return a > b
return False
class MaxFlow:
"""Dinic Algorithm: find max-flow
complexity: O(EV^2)
used in GRL6A(AOJ)
"""
class Edge:
def __init__(self, to, cap, rev):
self.to, self.cap, self.rev = to, cap, rev
def __init__(self, V, D):
""" V: the number of vertexes
E: adjacency list
source: start point
sink: goal point
"""
self.V = V
self.E = [[] for _ in range(V)]
self.D = D
def add_edge(self, fr, to, cap):
self.E[fr].append(self.Edge(to, cap, len(self.E[to])))
self.E[to].append(self.Edge(fr, [0] * self.D, len(self.E[fr])-1))
def dinic(self, source, sink):
"""find max-flow"""
INF = [10**9] * self.D
maxflow = [0] * self.D
while True:
self.bfs(source)
if self.level[sink] < 0:
return maxflow
self.itr = [0] * self.V
while True:
flow = self.dfs(source, sink, INF)
if gt_list(flow, [0] * self.D):
maxflow = plus_list(maxflow, flow)
else:
break
def dfs(self, vertex, sink, flow):
"""find augmenting path"""
if vertex == sink:
return flow
for i in range(self.itr[vertex], len(self.E[vertex])):
self.itr[vertex] = i
e = self.E[vertex][i]
if gt_list(e.cap, [0] * self.D) and self.level[vertex] < self.level[e.to]:
if gt_list(flow, e.cap):
d = self.dfs(e.to, sink, e.cap)
else:
d = self.dfs(e.to, sink, flow)
if gt_list(d, [0] * self.D):
e.cap = minus_list(e.cap, d)
self.E[e.to][e.rev].cap = plus_list(self.E[e.to][e.rev].cap, d)
return d
return [0] * self.D
def bfs(self, start):
"""find shortest path from start"""
que = collections.deque()
self.level = [-1] * self.V
que.append(start)
self.level[start] = 0
while que:
fr = que.popleft()
for e in self.E[fr]:
if gt_list(e.cap, [0] * self.D) and self.level[e.to] < 0:
self.level[e.to] = self.level[fr] + 1
que.append(e.to)
def to_poly(a, l):
if l == 0:
return str(a)
elif l == 1:
return "{}x".format('' if a == 1 else a)
else:
return "{}x^{}".format('' if a == 1 else a, l)
while True:
N, M = map(int, input().split())
if N == M == 0:
break
mf = MaxFlow(N, 51)
for _ in range(M):
u, v, p = input().split()
u, v = int(u)-1, int(v)-1
poly = [0] * 51
for x in p.split('+'):
try:
num = int(x)
poly[-1] = num
except ValueError:
a, l = x.split('x')
if l:
poly[-int(l.strip("^"))-1] = int(a) if a else 1
else:
poly[-2] = int(a) if a else 1
mf.add_edge(u, v, poly)
mf.add_edge(v, u, poly)
maxflow = mf.dinic(0, N-1)
ans = '+'.join(to_poly(a, l) for a, l in zip(maxflow, reversed(range(51))) if a)
print(ans if ans else 0)
```
| 96,039 |
Provide a correct Python 3 solution for this coding contest problem.
The trafic on the Internet is increasing these days due to smartphones. The wireless carriers have to enhance their network infrastructure.
The network of a wireless carrier consists of a number of base stations and lines. Each line connects two base stations bi-directionally. The bandwidth of a line increases every year and is given by a polynomial f(x) of the year x.
Your task is, given the network structure, to write a program to calculate the maximal bandwidth between the 1-st and N-th base stations as a polynomial of x.
Input
The input consists of multiple datasets. Each dataset has the following format:
N M
u1 v1 p1
...
uM vM pM
The first line of each dataset contains two integers N (2 ≤ N ≤ 50) and M (0 ≤ M ≤ 500), which indicates the number of base stations and lines respectively. The following M lines describe the network structure. The i-th of them corresponds to the i-th network line and contains two integers ui and vi and a polynomial pi. ui and vi indicate the indices of base stations (1 ≤ ui, vi ≤ N); pi indicates the network bandwidth.
Each polynomial has the form of:
aLxL + aL-1xL-1 + ... + a2x2 + a1x + a0
where L (0 ≤ L ≤ 50) is the degree and ai's (0 ≤ i ≤ L, 0 ≤ ai ≤ 100) are the coefficients. In the input,
* each term aixi (for i ≥ 2) is represented as <ai>x^<i>
* the linear term (a1x) is represented as <a1>x;
* the constant (a0) is represented just by digits;
* these terms are given in the strictly decreasing order of the degrees and connected by a plus sign ("+");
* just like the standard notations, the <ai> is omitted if ai = 1 for non-constant terms;
* similarly, the entire term is omitted if ai = 0 for any terms; and
* the polynomial representations contain no space or characters other than digits, "x", "^", and "+".
For example, 2x2 + 3x + 5 is represented as 2x^2+3x+5; 2x3 + x is represented as 2x^3+x, not 2x^3+0x^2+1x+0 or the like. No polynomial is a constant zero, i.e. the one with all the coefficients being zero.
The end of input is indicated by a line with two zeros. This line is not part of any dataset.
Output
For each dataset, print the maximal bandwidth as a polynomial of x. The polynomial should be represented in the same way as the input format except that a constant zero is possible and should be represented by "0" (without quotes).
Example
Input
3 3
1 2 x+2
2 3 2x+1
3 1 x+1
2 0
3 2
1 2 x
2 3 2
4 3
1 2 x^3+2x^2+3x+4
2 3 x^2+2x+3
3 4 x+2
0 0
Output
2x+3
0
2
x+2
"Correct Solution:
```
import sys
readline = sys.stdin.readline
write = sys.stdout.write
from string import digits
from collections import deque
class Dinic:
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap):
forward = [to, cap, None]
forward[2] = backward = [fr, 0, forward]
self.G[fr].append(forward)
self.G[to].append(backward)
def add_multi_edge(self, v1, v2, cap1, cap2):
edge1 = [v2, cap1, None]
edge1[2] = edge2 = [v1, cap2, edge1]
self.G[v1].append(edge1)
self.G[v2].append(edge2)
def bfs(self, s, t):
self.level = level = [None]*self.N
deq = deque([s])
level[s] = 0
G = self.G
while deq:
v = deq.popleft()
lv = level[v] + 1
for w, cap, _ in G[v]:
if cap and level[w] is None:
level[w] = lv
deq.append(w)
return level[t] is not None
def dfs(self, v, t, f):
if v == t:
return f
level = self.level
for e in self.it[v]:
w, cap, rev = e
if cap and level[v] < level[w]:
d = self.dfs(w, t, min(f, cap))
if d:
e[1] -= d
rev[1] += d
return d
return 0
def flow(self, s, t):
flow = 0
INF = 10**9 + 7
G = self.G
while self.bfs(s, t):
*self.it, = map(iter, self.G)
f = INF
while f:
f = self.dfs(s, t, INF)
flow += f
return flow
def parse(S, L=50):
S = S + "$"
E = [0]*(L+1)
cur = 0
while 1:
if S[cur] in digits:
k = 0
while S[cur] in digits:
k = 10*k + int(S[cur])
cur += 1 # '0' ~ '9'
else:
k = 1
if S[cur] == 'x':
cur += 1 # 'x'
if S[cur] == '^':
cur += 1 # '^'
p = 0
while S[cur] in digits:
p = 10*p + int(S[cur])
cur += 1 # '0' ~ '9'
else:
p = 1
else:
p = 0
E[p] = k
if S[cur] != '+':
break
cur += 1 # '+'
return E
def solve():
N, M = map(int, readline().split())
if N == 0:
return False
L = 50
ds = [Dinic(N) for i in range(L+1)]
for i in range(M):
u, v, p = readline().split()
u = int(u)-1; v = int(v)-1
poly = parse(p, L)
for j in range(L+1):
if poly[j] > 0:
ds[j].add_multi_edge(u, v, poly[j], poly[j])
INF = 10**9
res = [0]*(L+1)
for j in range(L+1):
f = ds[j].flow(0, N-1)
res[j] = f
E = [[0]*N for i in range(N)]
for j in range(L-1, -1, -1):
d = ds[j]
used = [0]*N
used[N-1] = 1
que = deque([N-1])
G = ds[j+1].G
for v in range(N):
for w, cap, _ in G[v]:
if cap:
E[v][w] = 1
for v in range(N):
for w in range(N):
if E[v][w]:
d.add_edge(v, w, INF)
f = d.flow(0, N-1)
res[j] += f
ans = []
if res[0] > 0:
ans.append(str(res[0]))
if res[1] > 0:
ans.append(("%dx" % res[1]) if res[1] > 1 else "x")
for i in range(2, L+1):
if res[i] > 0:
ans.append(("%dx^%d" % (res[i], i)) if res[i] > 1 else ("x^%d" % i))
if not ans:
ans.append("0")
ans.reverse()
write("+".join(ans))
write("\n")
return True
while solve():
...
```
| 96,040 |
Provide a correct Python 3 solution for this coding contest problem.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
"Correct Solution:
```
a,b,c = map(int,input().split())
lst = []
ans = 0
cnt = 0
while True:
s = (60*cnt+c) % (a+b)
if s in lst:
ans = -1
break
lst.append(s)
if 0 <= s <= a:
ans = 60 * cnt + c
break
cnt += 1
print(ans)
```
| 96,041 |
Provide a correct Python 3 solution for this coding contest problem.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
"Correct Solution:
```
a, b, c = map(int, input().split())
now = 0
used = [False] * 60
while True:
sleep_start = now + a
if now % 60 < sleep_start % 60:
if now % 60 <= c <= sleep_start % 60:
print(now // 60 * 60 + c)
break
now = sleep_start + b
else:
if now % 60 <= c < 60 or 0 < c <= sleep_start % 60:
print(now // 60 * 60 + c)
break
now = sleep_start + b
if now % 60 == 0:
print(-1)
break
```
| 96,042 |
Provide a correct Python 3 solution for this coding contest problem.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
"Correct Solution:
```
def solve(a, b, c):
l = 0; r = a;
for t in range(514):
t = l // 60
p = 60*t + c
if l <= p <= r:
print(p)
exit()
l = r + b
r = l + a
print(-1)
a, b, c = map(int, input().split())
solve(a,b,c)
```
| 96,043 |
Provide a correct Python 3 solution for this coding contest problem.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
"Correct Solution:
```
a, b, c = map(int, input().split())
passed = set()
time = 0
while True:
if time % 60 <= c <= time % 60 + a:
print(c + time // 60 * 60)
break
else:
time += a + b
if time % 60 in passed:
print(-1)
break
else:
passed.add(time % 60)
```
| 96,044 |
Provide a correct Python 3 solution for this coding contest problem.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
"Correct Solution:
```
a,b,c=map(int, input().split())
d=0
for _ in range(60):
if c<=d+a:
print(c)
break
d+=a+b
while c<=d:c+=60
else: print(-1)
```
| 96,045 |
Provide a correct Python 3 solution for this coding contest problem.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
"Correct Solution:
```
import sys
A,B,C = map(int,input().split())
time = 0
ss = set()
while True:
if time%60 == C:
print(time)
sys.exit()
for t in range(A):
time += 1
if time%60 == C:
print(time)
sys.exit()
time += B
if (time%60) in ss:
break
ss.add(time%60)
print(-1)
```
| 96,046 |
Provide a correct Python 3 solution for this coding contest problem.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
"Correct Solution:
```
A, B, C = map(int, input().split())
t = 0
while True:
t += A
if t >= C:
print(C)
break
t += B
if t > C:
C += 60
if t > 1000000:
print(-1)
break
```
| 96,047 |
Provide a correct Python 3 solution for this coding contest problem.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
"Correct Solution:
```
a, b, c = map(int, input().split())
l = 0; r = a;
for i in range(80):
t = l // 60
p = 60*t + c
if l <= p <= r:
print(p)
exit()
l = r + b
r = l + a
print(-1)
```
| 96,048 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
Submitted Solution:
```
def solve(a, b, c):
l = 0; r = a;
t = 0
for i in range(80):
t = l // 60
p = 60*t + c
if l <= p <= r:
print(p)
exit()
l = r + b
r = l + a
print(-1)
a, b, c = map(int, input().split())
solve(a,b,c)
```
Yes
| 96,049 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
while True:
a,b,c = LI()
s = set()
s.add(0)
t = 0
r = -1
for i in range(60):
while t > c:
c += 60
if t <= c <= t+a:
r = c
break
t += a + b
rr.append(r)
break
return '\n'.join(map(str, rr))
print(main())
```
Yes
| 96,050 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
Submitted Solution:
```
def solve(a, b, c):
l = 0; r = a;
for t in range(114514):
t = l // 60
p = 60*t + c
if l <= p <= r:
print(p)
exit()
l = r + b
r = l + a
print(-1)
a, b, c = map(int, input().split())
solve(a,b,c)
```
Yes
| 96,051 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
Submitted Solution:
```
import math
a, b, c = map(int, input().split())
for k in range(60):
t = math.ceil((k * (a + b) - c) / 60)
if t <= (k * (a + b) + a - c) / 60:
print(t * 60 + c)
break
else:
print(-1)
```
Yes
| 96,052 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
Submitted Solution:
```
from itertools import count
a,b,c=map(int,input().split())
f=False
for n in count(0):
p=(c+60*n)//(a+b)
if n and d==((a+b)*p-(c+60*n)) and e==((c+60*n)-((a+b)*p+a)):
n=-1
break
if (a+b)*p<=c+60*n<=(a+b)*p+a:
break
else:
d=(a+b)*p-(c+60*n)
e=(c+60*n)-((a+b)*p+a)
if n>=0:
print(c+60*n)
else:
print(n)
```
No
| 96,053 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
Submitted Solution:
```
def solve(a, b, c):
l = 0; r = a;
for t in range(114514):
p = 60*t + c
if l <= p <= r:
print(p)
exit()
l = r + b
r = l + a
print(-1)
a, b, c = map(int, input().split())
solve(a,b,c)
```
No
| 96,054 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
Submitted Solution:
```
from itertools import count
a,b,c=map(int,input().split())
for n in count(0):
if (a+b)*n<=c+60*n<=(a+b)*n+a:break
if n>0 and a+b<=60 and c>a:
n=-1
break
print(c+60*n)
```
No
| 96,055 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.
How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.
Constraints
* 0 <a, b, c <60
Input
The input is given in one line in the following format.
a b c
The input consists of three integers a, b, c.
a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.
Output
If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.
Examples
Input
10 10 5
Output
5
Input
50 40 51
Output
111
Input
20 20 20
Output
20
Input
30 30 40
Output
-1
Submitted Solution:
```
def solve(a, b, c):
l = 0; r = a;
for t in range(50):
t = l // 60
p = 60*t + c
if l <= p <= r:
print(p)
exit()
l = r + b
r = l + a
print(-1)
a, b, c = map(int, input().split())
solve(a,b,c)
```
No
| 96,056 |
Provide a correct Python 3 solution for this coding contest problem.
Problem statement
AOR Ika got a cabbage with $ N $ leaves. The leaves of this cabbage are numbered $ 1, \ ldots, N $ in order from the outside, and the dirtiness of the $ i $ th leaf is $ D_i $. The larger this value is, the worse the degree of dirt is. AOR Ika-chan decided to use the cabbage leaves for cooking, so she decided to select the dirty leaves to be discarded according to the following procedure.
1. Initialize the discard candidates to empty.
2. Focus on the outermost leaves that have not yet been examined. If all the items have been checked, the process ends.
3. If the leaf is dirty for $ A $ or more, add it to the discard candidate and return to 2. Otherwise it ends.
However, as a result of this operation, I noticed that the number of leaves that can be used for cooking may be extremely reduced. Therefore, I decided to reconsider the leaves to be discarded after the above operation and perform the following operations.
1. If there are less than $ M $ leaves that are not candidates for disposal, proceed to 2. Otherwise it ends.
2. Focus on the innermost leaf that has not been examined yet among the leaves that are candidates for disposal. If there are no leaves that are candidates for disposal, the process ends.
3. If the leaf is less than $ B $, remove it from the discard candidates and return to 2. Otherwise, discard all the leaves remaining in the discard candidates and finish.
When you perform these operations, find the number of leaves to be finally discarded.
Input constraints
$ 1 \ leq N \ leq 1000 $
$ 0 \ leq M \ leq N $
$ 1 \ leq A \ leq B \ leq 1000 $
$ 1 \ leq D_ {i} \ leq 1000 $
sample
Sample input 1
5 3 6 9
9 7 5 3 1
Sample output 1
2
Discard the first and second sheets.
Sample input 2
5 3 6 9
5 4 3 2 1
Sample output 2
0
Do not throw away from the first piece.
Sample input 3
5 3 6 9
10 8 6 4 2
Sample output 3
1
I tried to throw away the third one, but I reconsidered and decided not to throw away the second and third ones.
Sample input 4
5 3 6 9
5 10 8 6 4
Sample output 4
0
AOR Ika doesn't know that the second piece is dirty.
Sample input 5
5 0 6 9
9 9 8 8 7
Sample output 5
Five
I don't mind throwing everything away.
input
$ N \ M \ A \ B $
$ D_ {1} \ D_ {2} \ \ cdots \ D_ {N} $
output
Output the number of leaves to be finally thrown away.
Example
Input
5 3 6 9
9 7 5 3 1
Output
2
"Correct Solution:
```
#!/usr/bin/env python3
def solve(n, m, a, b, ds):
is_waste = [False for _ in range(n)]
for i in range(n):
if ds[i] >= a:
is_waste[i] = True
else:
break
if sum(is_waste) > n - m:
for i in range(n)[::-1]:
if is_waste[i]:
if ds[i] <= b:
is_waste[i] = False
else:
break
return sum(is_waste)
def main():
n, m, a, b = map(int, input().split())
ds = list(map(int, input().split()))
print(solve(n, m, a, b, ds))
if __name__ == '__main__':
main()
```
| 96,057 |
Provide a correct Python 3 solution for this coding contest problem.
N: Mail order
Mr. Komozawa bought building blocks toys from Makai mail order.
The building blocks are in the shape of a cube with a side length of 1, and are stacked on squares divided into $ H $ pieces vertically and $ W $ pieces horizontally.
Seen from the side, $ A_1, A_2, A_3, \ dots, A_H $ blocks were stacked in order from the left.
When viewed from the front, $ B_1, B_2, B_3, \ dots, B_W $ blocks were stacked in order from the left.
Mr. Komozawa is great, so I decided to guess the total number of blocks from this information alone.
If you answer a small number and make a mistake, it will be awkward, so I would like to answer the maximum number that can be considered.
input
The first line is given the integers $ H, W $, separated by blanks.
On the second line, $ H $ integers $ A_1, A_2, A_3, \ dots, A_H $ representing the figure when viewed from the side are given, separated by blanks.
On the third line, $ W $ integers $ B_1, B_2, B_3, \ dots, B_W $ representing the front view are given, separated by blanks.
output
Output the maximum number of blocks that can be considered from this information.
Constraint
* $ H, W $ are integers greater than or equal to $ 1 $ and less than or equal to $ 100 \ 000 $
* $ A_1, A_2, A_3, \ dots, A_H $ are integers greater than or equal to $ 1 $ and less than or equal to $ 100 \ 000 \ 000 $
* $ B_1, B_2, B_3, \ dots, B_W $ are integers greater than or equal to $ 1 $ and less than or equal to $ 100 \ 000 \ 000 $
* It is guaranteed that there is a stacking method of blocks that meets the conditions for all inputs.
Input example 1
twenty two
1 5
1 5
Output example 1
8
Let's represent the $ X $ th cell in the vertical direction and the $ Y $ th cell in the horizontal direction by $ (X, Y) $.
A total of $ 8 $ if 5 pieces are stacked on the mass $ (2, 2) $ and $ 1 $ is stacked on the mass $ (1, 1) $, $ (1, 2) $, $ (2, 1) $. Blocks will be piled up.
The answer is $ 8 $, as it is unlikely that you have more than $ 9 $.
Input example 2
3 3
2 4 5
3 1 5
Output example 2
twenty two
Example
Input
2 2
1 5
1 5
Output
8
"Correct Solution:
```
from bisect import bisect_left as bl
from itertools import accumulate
h, w= map(int, input().split())
aList = sorted(map(int, input().split()))
bList = list(map(int, input().split()))
acc = [0]+list(accumulate(aList))
aList.insert(0, -1)
ans = 0
for b in bList:
index = bl(aList, b)
ans += acc[index - 1] + (h - index + 1) * b
print(ans)
```
| 96,058 |
Provide a correct Python 3 solution for this coding contest problem.
Problem
There are coins with front and back sides and dice with rolls from $ 1 $ to $ N $. Gacho decided to play the following games using these.
The game starts with a score of $ 0 $ and proceeds as follows.
1. Roll the dice $ 1 $ and add the number of rolls to the score.
2. If the current score is $ K $ or more, the game is cleared and the game ends.
3. If the current score is less than $ K $, toss a coin and return to 1. if the front appears, and if the back appears, the game is over and the game ends.
When a coin is thrown, it has a probability of $ A \% $ and a probability of $ (100-A) \% $. Also, when the dice are rolled, each eye appears with equal probability.
At this time, find the probability that Gacho can clear the game in one game.
When the probability to be calculated is expressed as $ \ frac {P} {Q} $ using relatively prime integers $ P and Q $, it becomes $ R \ times Q \ equiv P \ bmod 998244353 $ $ 0 $ or more and $ 998244352 $ or less. Output the integer $ R $ of. Under the constraints of this problem, such $ R $ always exists uniquely.
Constraints
The input satisfies the following conditions.
* $ 1 \ leq N \ leq 10 ^ 5 $
* $ 1 \ leq K \ leq 10 ^ 5 $
* $ 1 \ leq A \ leq 99 $
* All inputs are integers
Input
The input is given in the following format.
$ N $ $ K $ $ A $
$ N, K, A $ are given on one line separated by blanks.
Output
When the probability of clearing the game is expressed as $ \ frac {P} {Q} $ using relatively prime integers $ P and Q $, it becomes $ R \ times Q \ equiv P \ bmod 998244353 $. Output an integer $ R $ that is greater than or equal to $ 0 $ and less than or equal to $ 998244352 $.
Examples
Input
1 1 50
Output
1
Input
2 2 10
Output
648858830
Input
6 10 99
Output
650893870
"Correct Solution:
```
N, K, A = map(int, input().split())
dp = [0] * (K+1) + [1] * N # 残りが i 点のときの勝率
dp[0] = 1
c = 1
mod = 998244353
p_coin = A * pow(100, mod-2, mod) % mod
p_dice = pow(N, mod-2, mod)
for i in range(1, K+1):
dp[i] = c * p_coin % mod
c += (dp[i] - dp[i-N]) * p_dice % mod
print(dp[K] * pow(p_coin, mod-2, mod) % mod)
```
| 96,059 |
Provide a correct Python 3 solution for this coding contest problem.
Problem
There are coins with front and back sides and dice with rolls from $ 1 $ to $ N $. Gacho decided to play the following games using these.
The game starts with a score of $ 0 $ and proceeds as follows.
1. Roll the dice $ 1 $ and add the number of rolls to the score.
2. If the current score is $ K $ or more, the game is cleared and the game ends.
3. If the current score is less than $ K $, toss a coin and return to 1. if the front appears, and if the back appears, the game is over and the game ends.
When a coin is thrown, it has a probability of $ A \% $ and a probability of $ (100-A) \% $. Also, when the dice are rolled, each eye appears with equal probability.
At this time, find the probability that Gacho can clear the game in one game.
When the probability to be calculated is expressed as $ \ frac {P} {Q} $ using relatively prime integers $ P and Q $, it becomes $ R \ times Q \ equiv P \ bmod 998244353 $ $ 0 $ or more and $ 998244352 $ or less. Output the integer $ R $ of. Under the constraints of this problem, such $ R $ always exists uniquely.
Constraints
The input satisfies the following conditions.
* $ 1 \ leq N \ leq 10 ^ 5 $
* $ 1 \ leq K \ leq 10 ^ 5 $
* $ 1 \ leq A \ leq 99 $
* All inputs are integers
Input
The input is given in the following format.
$ N $ $ K $ $ A $
$ N, K, A $ are given on one line separated by blanks.
Output
When the probability of clearing the game is expressed as $ \ frac {P} {Q} $ using relatively prime integers $ P and Q $, it becomes $ R \ times Q \ equiv P \ bmod 998244353 $. Output an integer $ R $ that is greater than or equal to $ 0 $ and less than or equal to $ 998244352 $.
Examples
Input
1 1 50
Output
1
Input
2 2 10
Output
648858830
Input
6 10 99
Output
650893870
"Correct Solution:
```
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
res = list(sys.stdin.readline())
if res[-1] == "\n":
return res[:-1]
return res
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 998244353
def solve():
n,k,a = LI()
lst = [0]*(k+1)
lst[-2] = 1
A = a*pow(100*n,mod-2,mod)
inv = pow(n,mod-2,mod)
for i in range(k-1)[::-1]:
if k > i + n:
lst[i] = A*(lst[i+1] - lst[i+n+1]) + lst[i+1]
lst[i] %= mod
else:
lst[i] = A*(lst[i+1] - lst[k]) + (n-(k-i)+1)*inv + lst[i+1]
lst[i] %= mod
print((lst[0] - lst[1])%mod)
return
if __name__ == "__main__":
solve()
```
| 96,060 |
Provide a correct Python 3 solution for this coding contest problem.
Find common tangent lines of two circles $c1$ and $c2$.
Constraints
* $-1,000 \leq c1x, c1y, c2x, c2y \leq 1,000$
* $1 \leq c1r, c2r \leq 1,000$
* $c1$ and $c2$ are different
Input
Center coordinates ($cix$, $ciy$) and radii $cir$ of two circles $c1$ are $c2$ are given in the following format.
$c1x \; c1y \; c1r$
$c2x \; c2y \; c2r$
All input values are given in integers.
Output
Print coordinates of the tangent points on circle $c1$ based on the following rules.
* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.
The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
1 1 1
6 2 2
Output
0.6153846154 1.9230769231
1.0000000000 0.0000000000
1.4183420913 1.9082895434
1.7355040625 0.3224796874
Input
1 2 1
4 2 2
Output
0.6666666667 1.0571909584
0.6666666667 2.9428090416
2.0000000000 2.0000000000
Input
1 2 1
3 2 2
Output
0.5000000000 1.1339745962
0.5000000000 2.8660254038
Input
0 0 1
1 0 2
Output
-1.0000000000 0.0000000000
Input
0 0 1
0 0 2
Output
"Correct Solution:
```
import cmath
import itertools
import math
import os
import sys
from collections import defaultdict
if os.getenv("LOCAL"):
sys.stdin = open("_in.txt", "r")
sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353
PI = cmath.pi
TAU = cmath.pi * 2
EPS = 1e-10
class Point:
"""
2次元空間上の点
"""
# 反時計回り側にある
CCW_COUNTER_CLOCKWISE = 1
# 時計回り側にある
CCW_CLOCKWISE = -1
# 線分の後ろにある
CCW_ONLINE_BACK = 2
# 線分の前にある
CCW_ONLINE_FRONT = -2
# 線分上にある
CCW_ON_SEGMENT = 0
def __init__(self, c: complex):
self.c = c
@property
def x(self):
return self.c.real
@property
def y(self):
return self.c.imag
@staticmethod
def from_rect(x: float, y: float):
return Point(complex(x, y))
@staticmethod
def from_polar(r: float, phi: float):
return Point(cmath.rect(r, phi))
def __add__(self, p):
"""
:param Point p:
"""
return Point(self.c + p.c)
def __iadd__(self, p):
"""
:param Point p:
"""
self.c += p.c
return self
def __sub__(self, p):
"""
:param Point p:
"""
return Point(self.c - p.c)
def __isub__(self, p):
"""
:param Point p:
"""
self.c -= p.c
return self
def __mul__(self, f: float):
return Point(self.c * f)
def __imul__(self, f: float):
self.c *= f
return self
def __truediv__(self, f: float):
return Point(self.c / f)
def __itruediv__(self, f: float):
self.c /= f
return self
def __repr__(self):
return "({}, {})".format(round(self.x, 10), round(self.y, 10))
def __neg__(self):
return Point(-self.c)
def __eq__(self, p):
return abs(self.c - p.c) < EPS
def __abs__(self):
return abs(self.c)
@staticmethod
def ccw(a, b, c):
"""
線分 ab に対する c の位置
線分上にあるか判定するだけなら on_segment とかのが速い
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C&lang=ja
:param Point a:
:param Point b:
:param Point c:
"""
b = b - a
c = c - a
det = b.det(c)
if det > EPS:
return Point.CCW_COUNTER_CLOCKWISE
if det < -EPS:
return Point.CCW_CLOCKWISE
if b.dot(c) < -EPS:
return Point.CCW_ONLINE_BACK
if c.norm() - b.norm() > EPS:
return Point.CCW_ONLINE_FRONT
return Point.CCW_ON_SEGMENT
def dot(self, p):
"""
内積
:param Point p:
:rtype: float
"""
return self.x * p.x + self.y * p.y
def det(self, p):
"""
外積
:param Point p:
:rtype: float
"""
return self.x * p.y - self.y * p.x
def dist(self, p):
"""
距離
:param Point p:
:rtype: float
"""
return abs(self.c - p.c)
def norm(self):
"""
原点からの距離
:rtype: float
"""
return abs(self.c)
def phase(self):
"""
原点からの角度
:rtype: float
"""
return cmath.phase(self.c)
def angle(self, p, q):
"""
p に向いてる状態から q まで反時計回りに回転するときの角度
-pi <= ret <= pi
:param Point p:
:param Point q:
:rtype: float
"""
return (cmath.phase(q.c - self.c) - cmath.phase(p.c - self.c) + PI) % TAU - PI
def area(self, p, q):
"""
p, q となす三角形の面積
:param Point p:
:param Point q:
:rtype: float
"""
return abs((p - self).det(q - self) / 2)
def projection_point(self, p, q, allow_outer=False):
"""
線分 pq を通る直線上に垂線をおろしたときの足の座標
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A&lang=ja
:param Point p:
:param Point q:
:param allow_outer: 答えが線分の間になくても OK
:rtype: Point|None
"""
diff_q = q - p
# 答えの p からの距離
r = (self - p).dot(diff_q) / abs(diff_q)
# 線分の角度
phase = diff_q.phase()
ret = Point.from_polar(r, phase) + p
if allow_outer or (p - ret).dot(q - ret) < EPS:
return ret
return None
def reflection_point(self, p, q):
"""
直線 pq を挟んで反対にある点
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B&lang=ja
:param Point p:
:param Point q:
:rtype: Point
"""
# 距離
r = abs(self - p)
# pq と p-self の角度
angle = p.angle(q, self)
# 直線を挟んで角度を反対にする
angle = (q - p).phase() - angle
return Point.from_polar(r, angle) + p
def on_segment(self, p, q, allow_side=True):
"""
点が線分 pq の上に乗っているか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C&lang=ja
:param Point p:
:param Point q:
:param allow_side: 端っこでギリギリ触れているのを許容するか
:rtype: bool
"""
if not allow_side and (self == p or self == q):
return False
# 外積がゼロ: 面積がゼロ == 一直線
# 内積がマイナス: p - self - q の順に並んでる
return abs((p - self).det(q - self)) < EPS and (p - self).dot(q - self) < EPS
class Line:
"""
2次元空間上の直線
"""
def __init__(self, a: float, b: float, c: float):
"""
直線 ax + by + c = 0
"""
self.a = a
self.b = b
self.c = c
@staticmethod
def from_gradient(grad: float, intercept: float):
"""
直線 y = ax + b
:param grad: 傾き
:param intercept: 切片
:return:
"""
return Line(grad, -1, intercept)
@staticmethod
def from_segment(p1, p2):
"""
:param Point p1:
:param Point p2:
"""
a = p2.y - p1.y
b = p1.x - p2.x
c = p2.y * (p2.x - p1.x) - p2.x * (p2.y - p1.y)
return Line(a, b, c)
@property
def gradient(self):
"""
傾き
"""
return INF if self.b == 0 else -self.a / self.b
@property
def intercept(self):
"""
切片
"""
return INF if self.b == 0 else -self.c / self.b
def is_parallel_to(self, l):
"""
平行かどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja
:param Line l:
"""
# 法線ベクトル同士の外積がゼロ
return abs(Point.from_rect(self.a, self.b).det(Point.from_rect(l.a, l.b))) < EPS
def is_orthogonal_to(self, l):
"""
直行しているかどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja
:param Line l:
"""
# 法線ベクトル同士の内積がゼロ
return abs(Point.from_rect(self.a, self.b).dot(Point.from_rect(l.a, l.b))) < EPS
def intersection_point(self, l):
"""
交差する点
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C&lang=ja
:param Line l:
:rtype: Point|None
"""
a1, b1, c1 = self.a, self.b, self.c
a2, b2, c2 = l.a, l.b, l.c
det = a1 * b2 - a2 * b1
if abs(det) < EPS:
# 並行
return None
x = (b1 * c2 - b2 * c1) / det
y = (a2 * c1 - a1 * c2) / det
return Point.from_rect(x, y)
def dist(self, p):
"""
他の点との最短距離
:param Point p:
"""
raise NotImplementedError()
def has_point(self, p):
"""
p が直線上に乗っているかどうか
:param Point p:
"""
return abs(self.a * p.x + self.b * p.y + self.c) < EPS
class Segment:
"""
2次元空間上の線分
"""
def __init__(self, p1, p2):
"""
:param Point p1:
:param Point p2:
"""
self.p1 = p1
self.p2 = p2
def norm(self):
"""
線分の長さ
"""
return abs(self.p1 - self.p2)
def phase(self):
"""
p1 を原点としたときの p2 の角度
"""
return (self.p2 - self.p1).phase()
def is_parallel_to(self, s):
"""
平行かどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja
:param Segment s:
:return:
"""
# 外積がゼロ
return abs((self.p1 - self.p2).det(s.p1 - s.p2)) < EPS
def is_orthogonal_to(self, s):
"""
直行しているかどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja
:param Segment s:
:return:
"""
# 内積がゼロ
return abs((self.p1 - self.p2).dot(s.p1 - s.p2)) < EPS
def intersects_with(self, s, allow_side=True):
"""
交差するかどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B&lang=ja
:param Segment s:
:param allow_side: 端っこでギリギリ触れているのを許容するか
"""
if self.is_parallel_to(s):
# 並行なら線分の端点がもう片方の線分の上にあるかどうか
return (s.p1.on_segment(self.p1, self.p2, allow_side) or
s.p2.on_segment(self.p1, self.p2, allow_side) or
self.p1.on_segment(s.p1, s.p2, allow_side) or
self.p2.on_segment(s.p1, s.p2, allow_side))
else:
# allow_side ならゼロを許容する
det_upper = EPS if allow_side else -EPS
ok = True
# self の両側に s.p1 と s.p2 があるか
ok &= (self.p2 - self.p1).det(s.p1 - self.p1) * (self.p2 - self.p1).det(s.p2 - self.p1) < det_upper
# s の両側に self.p1 と self.p2 があるか
ok &= (s.p2 - s.p1).det(self.p1 - s.p1) * (s.p2 - s.p1).det(self.p2 - s.p1) < det_upper
return ok
def closest_point(self, p):
"""
線分上の、p に最も近い点
:param Point p:
"""
# p からおろした垂線までの距離
d = (p - self.p1).dot(self.p2 - self.p1) / self.norm()
# p1 より前
if d < EPS:
return self.p1
# p2 より後
if -EPS < d - self.norm():
return self.p2
# 線分上
return Point.from_polar(d, (self.p2 - self.p1).phase()) + self.p1
def dist(self, p):
"""
他の点との最短距離
:param Point p:
"""
return abs(p - self.closest_point(p))
def dist_segment(self, s):
"""
他の線分との最短距離
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D&lang=ja
:param Segment s:
"""
if self.intersects_with(s):
return 0.0
return min(
self.dist(s.p1),
self.dist(s.p2),
s.dist(self.p1),
s.dist(self.p2),
)
def has_point(self, p, allow_side=True):
"""
p が線分上に乗っているかどうか
:param Point p:
:param allow_side: 端っこでギリギリ触れているのを許容するか
"""
return p.on_segment(self.p1, self.p2, allow_side=allow_side)
class Polygon:
"""
2次元空間上の多角形
"""
def __init__(self, points):
"""
:param list of Point points:
"""
self.points = points
def iter2(self):
"""
隣り合う2点を順に返すイテレータ
:rtype: typing.Iterator[(Point, Point)]
"""
return zip(self.points, self.points[1:] + self.points[:1])
def iter3(self):
"""
隣り合う3点を順に返すイテレータ
:rtype: typing.Iterator[(Point, Point, Point)]
"""
return zip(self.points,
self.points[1:] + self.points[:1],
self.points[2:] + self.points[:2])
def area(self):
"""
面積
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A&lang=ja
"""
# 外積の和 / 2
dets = []
for p, q in self.iter2():
dets.append(p.det(q))
return abs(math.fsum(dets)) / 2
def is_convex(self, allow_straight=False, allow_collapsed=False):
"""
凸多角形かどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B&lang=ja
:param allow_straight: 3点がまっすぐ並んでるのを許容するかどうか
:param allow_collapsed: 面積がゼロの場合を許容するか
"""
ccw = []
for a, b, c in self.iter3():
ccw.append(Point.ccw(a, b, c))
ccw = set(ccw)
if len(ccw) == 1:
if ccw == {Point.CCW_CLOCKWISE}:
return True
if ccw == {Point.CCW_COUNTER_CLOCKWISE}:
return True
if allow_straight and len(ccw) == 2:
if ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_CLOCKWISE}:
return True
if ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_COUNTER_CLOCKWISE}:
return True
if allow_collapsed and len(ccw) == 3:
return ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_ONLINE_BACK, Point.CCW_ON_SEGMENT}
return False
def has_point_on_edge(self, p):
"""
指定した点が辺上にあるか
:param Point p:
:rtype: bool
"""
for a, b in self.iter2():
if p.on_segment(a, b):
return True
return False
def contains(self, p, allow_on_edge=True):
"""
指定した点を含むか
Winding Number Algorithm
https://www.nttpc.co.jp/technology/number_algorithm.html
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C&lang=ja
:param Point p:
:param bool allow_on_edge: 辺上の点を許容するか
"""
angles = []
for a, b in self.iter2():
if p.on_segment(a, b):
return allow_on_edge
angles.append(p.angle(a, b))
# 一周以上するなら含む
return abs(math.fsum(angles)) > EPS
@staticmethod
def convex_hull(points, allow_straight=False):
"""
凸包。x が最も小さい点のうち y が最も小さい点から反時計回り。
Graham Scan O(N log N)
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A&lang=ja
:param list of Point points:
:param allow_straight: 3点がまっすぐ並んでるのを許容するかどうか
:rtype: list of Point
"""
points = points[:]
points.sort(key=lambda p: (p.x, p.y))
# allow_straight なら 0 を許容する
det_lower = -EPS if allow_straight else EPS
sz = 0
#: :type: list of (Point|None)
ret = [None] * (len(points) * 2)
for p in points:
while sz > 1 and (ret[sz - 1] - ret[sz - 2]).det(p - ret[sz - 1]) < det_lower:
sz -= 1
ret[sz] = p
sz += 1
floor = sz
for p in reversed(points[:-1]):
while sz > floor and (ret[sz - 1] - ret[sz - 2]).det(p - ret[sz - 1]) < det_lower:
sz -= 1
ret[sz] = p
sz += 1
ret = ret[:sz - 1]
if allow_straight and len(ret) > len(points):
# allow_straight かつ全部一直線のときに二重にカウントしちゃう
ret = points
return ret
@staticmethod
def diameter(points):
"""
直径
凸包構築 O(N log N) + カリパー法 O(N)
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B&lang=ja
:param list of Point points:
"""
# 反時計回り
points = Polygon.convex_hull(points, allow_straight=False)
if len(points) == 1:
return 0.0
if len(points) == 2:
return abs(points[0] - points[1])
# x軸方向に最も遠い点対
si = points.index(min(points, key=lambda p: (p.x, p.y)))
sj = points.index(max(points, key=lambda p: (p.x, p.y)))
n = len(points)
ret = 0.0
# 半周回転
i, j = si, sj
while i != sj or j != si:
ret = max(ret, abs(points[i] - points[j]))
ni = (i + 1) % n
nj = (j + 1) % n
# 2つの辺が並行になる方向にずらす
if (points[ni] - points[i]).det(points[nj] - points[j]) > 0:
j = nj
else:
i = ni
return ret
def convex_cut_by_line(self, line_p1, line_p2):
"""
凸多角形を直線 line_p1-line_p2 でカットする。
凸じゃないといけません
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C&lang=ja
:param line_p1:
:param line_p2:
:return: (line_p1-line_p2 の左側の多角形, line_p1-line_p2 の右側の多角形)
:rtype: (Polygon|None, Polygon|None)
"""
n = len(self.points)
line = Line.from_segment(line_p1, line_p2)
# 直線と重なる点
on_line_points = []
for i, p in enumerate(self.points):
if line.has_point(p):
on_line_points.append(i)
# 辺が直線上にある
has_on_line_edge = False
if len(on_line_points) >= 3:
has_on_line_edge = True
elif len(on_line_points) == 2:
# 直線上にある点が隣り合ってる
has_on_line_edge = abs(on_line_points[0] - on_line_points[1]) in [1, n - 1]
# 辺が直線上にある場合、どっちか片方に全部ある
if has_on_line_edge:
for p in self.points:
ccw = Point.ccw(line_p1, line_p2, p)
if ccw == Point.CCW_COUNTER_CLOCKWISE:
return Polygon(self.points[:]), None
if ccw == Point.CCW_CLOCKWISE:
return None, Polygon(self.points[:])
ret_lefts = []
ret_rights = []
d = line_p2 - line_p1
for p, q in self.iter2():
det_p = d.det(p - line_p1)
det_q = d.det(q - line_p1)
if det_p > -EPS:
ret_lefts.append(p)
if det_p < EPS:
ret_rights.append(p)
# 外積の符号が違う == 直線の反対側にある場合は交点を追加
if det_p * det_q < -EPS:
intersection = line.intersection_point(Line.from_segment(p, q))
ret_lefts.append(intersection)
ret_rights.append(intersection)
# 点のみの場合を除いて返す
l = Polygon(ret_lefts) if len(ret_lefts) > 1 else None
r = Polygon(ret_rights) if len(ret_rights) > 1 else None
return l, r
def closest_pair(points):
"""
最近点対 O(N log N)
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A&lang=ja
:param list of Point points:
:rtype: (float, (Point, Point))
:return: (距離, 点対)
"""
assert len(points) >= 2
def _rec(xsorted):
"""
:param list of Point xsorted:
:rtype: (float, (Point, Point))
"""
n = len(xsorted)
if n <= 2:
return xsorted[0].dist(xsorted[1]), (xsorted[0], xsorted[1])
if n <= 3:
# 全探索
d = INF
pair = None
for p, q in itertools.combinations(xsorted, r=2):
if p.dist(q) < d:
d = p.dist(q)
pair = p, q
return d, pair
# 分割統治
# 両側の最近点対
ld, lp = _rec(xsorted[:n // 2])
rd, rp = _rec(xsorted[n // 2:])
if ld <= rd:
d = ld
ret_pair = lp
else:
d = rd
ret_pair = rp
mid_x = xsorted[n // 2].x
# 中央から d 以内のやつを集める
mid_points = []
for p in xsorted:
# if abs(p.x - mid_x) < d:
if abs(p.x - mid_x) - d < -EPS:
mid_points.append(p)
# この中で距離が d 以内のペアがあれば更新
mid_points.sort(key=lambda p: p.y)
mid_n = len(mid_points)
for i in range(mid_n - 1):
j = i + 1
p = mid_points[i]
q = mid_points[j]
# while q.y - p.y < d
while (q.y - p.y) - d < -EPS:
pq_d = p.dist(q)
if pq_d < d:
d = pq_d
ret_pair = p, q
j += 1
if j >= mid_n:
break
q = mid_points[j]
return d, ret_pair
return _rec(list(sorted(points, key=lambda p: p.x)))
def closest_pair_randomized(points):
"""
最近点対 乱択版 O(N)
http://ir5.hatenablog.com/entry/20131221/1387557630
グリッドの管理が dict だから定数倍気になる
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A&lang=ja
:param list of Point points:
:rtype: (float, (Point, Point))
:return: (距離, 点対)
"""
n = len(points)
assert n >= 2
if n == 2:
return points[0].dist(points[1]), (points[0], points[1])
# 逐次構成法
import random
points = points[:]
random.shuffle(points)
DELTA_XY = list(itertools.product([-1, 0, 1], repeat=2))
grid = defaultdict(list)
delta = INF
dist = points[0].dist(points[1])
ret_pair = points[0], points[1]
for i in range(2, n):
if delta < EPS:
return 0.0, ret_pair
# i 番目より前までを含む grid を構築
# if dist < delta:
if dist - delta < -EPS:
delta = dist
grid = defaultdict(list)
for a in points[:i]:
grid[a.x // delta, a.y // delta].append(a)
else:
p = points[i - 1]
grid[p.x // delta, p.y // delta].append(p)
p = points[i]
dist = delta
grid_x = p.x // delta
grid_y = p.y // delta
# 周り 9 箇所だけ調べれば OK
for dx, dy in DELTA_XY:
for q in grid[grid_x + dx, grid_y + dy]:
d = p.dist(q)
# if d < dist:
if d - dist < -EPS:
dist = d
ret_pair = p, q
return min(delta, dist), ret_pair
class Circle:
def __init__(self, o, r):
"""
:param Point o:
:param float r:
"""
self.o = o
self.r = r
def __eq__(self, other):
return self.o == other.o and abs(self.r - other.r) < EPS
def ctc(self, c):
"""
共通接線 common tangent の数
4: 離れてる
3: 外接
2: 交わってる
1: 内接
0: 内包
inf: 同一
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_A&lang=ja
:param Circle c:
:rtype: int
"""
if self.o == c.o:
return INF if abs(self.r - c.r) < EPS else 0
# 円同士の距離
d = self.o.dist(c.o) - self.r - c.r
if d > EPS:
return 4
elif d > -EPS:
return 3
# elif d > -min(self.r, c.r) * 2:
elif d + min(self.r, c.r) * 2 > EPS:
return 2
elif d + min(self.r, c.r) * 2 > -EPS:
return 1
return 0
def area(self):
"""
面積
"""
return self.r ** 2 * PI
def intersection_points(self, other, allow_outer=False):
"""
:param Segment|Circle other:
:param bool allow_outer:
"""
if isinstance(other, Segment):
return self.intersection_points_with_segment(other, allow_outer=allow_outer)
if isinstance(other, Circle):
return self.intersection_points_with_circle(other)
raise NotImplementedError()
def intersection_points_with_segment(self, s, allow_outer=False):
"""
線分と交差する点のリスト
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_D&lang=ja
:param Segment s:
:param bool allow_outer: 線分の間にない点を含む
:rtype: list of Point
"""
# 垂線の足
projection_point = self.o.projection_point(s.p1, s.p2, allow_outer=True)
# 線分との距離
dist = self.o.dist(projection_point)
# if dist > self.r:
if dist - self.r > EPS:
return []
if dist - self.r > -EPS:
if allow_outer or s.has_point(projection_point):
return [projection_point]
else:
return []
# 足から左右に diff だけ動かした座標が答え
diff = Point.from_polar(math.sqrt(self.r ** 2 - dist ** 2), s.phase())
ret1 = projection_point + diff
ret2 = projection_point - diff
ret = []
if allow_outer or s.has_point(ret1):
ret.append(ret1)
if allow_outer or s.has_point(ret2):
ret.append(ret2)
return ret
def intersection_points_with_circle(self, other):
"""
円と交差する点のリスト
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_E&langja
:param circle other:
:rtype: list of Point
"""
ctc = self.ctc(other)
if not 1 <= ctc <= 3:
return []
if ctc == 3:
# 外接
return [Point.from_polar(self.r, (other.o - self.o).phase()) + self.o]
if ctc == 1:
# 内接
if self.r > other.r:
return [Point.from_polar(self.r, (other.o - self.o).phase()) + self.o]
else:
return [Point.from_polar(self.r, (self.o - other.o).phase()) + self.o]
# 2つ交点がある
assert ctc == 2
a = other.r
b = self.r
c = self.o.dist(other.o)
# 余弦定理で cos(a) を求めます
cos_a = (b ** 2 + c ** 2 - a ** 2) / (2 * b * c)
angle = math.acos(cos_a)
phi = (other.o - self.o).phase()
return [
self.o + Point.from_polar(self.r, phi + angle),
self.o + Point.from_polar(self.r, phi - angle),
]
def tangent_points_with_point(self, p):
"""
p を通る接線との接点
:param Point p:
:rtype: list of Point
"""
dist = self.o.dist(p)
# if dist < self.r:
if dist - self.r < -EPS:
# p が円の内部にある
return []
if dist - self.r < EPS:
# p が円周上にある
return [Point(p.c)]
a = math.sqrt(dist ** 2 - self.r ** 2)
b = self.r
c = dist
# 余弦定理で cos(a) を求めます
cos_a = (b ** 2 + c ** 2 - a ** 2) / (2 * b * c)
angle = math.acos(cos_a)
phi = (p - self.o).phase()
return [
self.o + Point.from_polar(self.r, phi + angle),
self.o + Point.from_polar(self.r, phi - angle),
]
def tangent_points_with_circle(self, other):
"""
other との共通接線との接点
:param Circle other:
:rtype: list of Point
"""
ctc = self.ctc(other)
if ctc > 4:
raise ValueError('2つの円が同一です')
if ctc == 0:
return []
if ctc == 1:
return self.intersection_points_with_circle(other)
assert ctc in (2, 3, 4)
ret = []
# 共通外接線を求める
# if self.r == other.r:
if abs(self.r - other.r) < EPS:
# 半径が同じ == 2つの共通外接線が並行
phi = (other.o - self.o).phase()
ret.append(self.o + Point.from_polar(self.r, phi + PI / 2))
ret.append(self.o + Point.from_polar(self.r, phi - PI / 2))
else:
# 2つの共通外接線の交点から接線を引く
intersection = self.o + (other.o - self.o) / (self.r - other.r) * self.r
ret += self.tangent_points_with_point(intersection)
# 共通内接線を求める
# 2つの共通内接線の交点から接線を引く
intersection = self.o + (other.o - self.o) / (self.r + other.r) * self.r
ret += self.tangent_points_with_point(intersection)
return ret
def round_point(p):
"""
8桁で四捨五入して、-0を0に変換する
:param p:
:return:
"""
return round(p.x, 10) + 0, round(p.y, 10) + 0
x1, y1, r1 = list(map(int, sys.stdin.buffer.readline().split()))
x2, y2, r2 = list(map(int, sys.stdin.buffer.readline().split()))
c1 = Circle(Point(complex(x1, y1)), r1)
c2 = Circle(Point(complex(x2, y2)), r2)
ans = c1.tangent_points_with_circle(c2)
for x, y in sorted(map(round_point, ans)):
print('{:.10f} {:.10f}'.format(x, y))
```
| 96,061 |
Provide a correct Python 3 solution for this coding contest problem.
Find common tangent lines of two circles $c1$ and $c2$.
Constraints
* $-1,000 \leq c1x, c1y, c2x, c2y \leq 1,000$
* $1 \leq c1r, c2r \leq 1,000$
* $c1$ and $c2$ are different
Input
Center coordinates ($cix$, $ciy$) and radii $cir$ of two circles $c1$ are $c2$ are given in the following format.
$c1x \; c1y \; c1r$
$c2x \; c2y \; c2r$
All input values are given in integers.
Output
Print coordinates of the tangent points on circle $c1$ based on the following rules.
* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.
The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
1 1 1
6 2 2
Output
0.6153846154 1.9230769231
1.0000000000 0.0000000000
1.4183420913 1.9082895434
1.7355040625 0.3224796874
Input
1 2 1
4 2 2
Output
0.6666666667 1.0571909584
0.6666666667 2.9428090416
2.0000000000 2.0000000000
Input
1 2 1
3 2 2
Output
0.5000000000 1.1339745962
0.5000000000 2.8660254038
Input
0 0 1
1 0 2
Output
-1.0000000000 0.0000000000
Input
0 0 1
0 0 2
Output
"Correct Solution:
```
#!/usr/bin/env python3
# CGL_7_G: Circles - Common Tangent
from math import acos, atan2, cos, hypot, isclose, pi, sin
def tangent_points(circle1, circle2):
x1, y1, r1 = circle1
x2, y2, r2 = circle2
c1c2 = hypot(x2-x1, y2-y1)
t0 = atan2(y2-y1, x2-x1)
ps = []
r1r2 = r1+r2
if isclose(c1c2, r1r2):
ps.append((x1 + r1*cos(t0), y1 + r1*sin(t0)))
elif c1c2 > r1r2:
t1 = acos(r1r2 / c1c2)
ps.append((x1 + r1*cos(t0+t1), y1 + r1*sin(t0+t1)))
ps.append((x1 + r1*cos(t0-t1), y1 + r1*sin(t0-t1)))
r1r2 = r1-r2
if isclose(c1c2, abs(r1r2)):
if r1r2 > 0.0:
t1 = 0.0
else:
t1 = pi
ps.append((x1 + r1*cos(t0+t1), y1 + r1*sin(t0+t1)))
elif c1c2 > abs(r1r2):
if r1r2 > 0.0:
t1 = acos(r1r2 / c1c2)
else:
t1 = pi - acos(-r1r2 / c1c2)
ps.append((x1 + r1*cos(t0+t1), y1 + r1*sin(t0+t1)))
ps.append((x1 + r1*cos(t0-t1), y1 + r1*sin(t0-t1)))
return ps
def run():
c1 = [int(i) for i in input().split()]
c2 = [int(i) for i in input().split()]
ps = tangent_points(c1, c2)
for p in sorted(ps):
print("{:.10f} {:.10f}".format(*map(eliminate_minus_zero, p)))
def eliminate_minus_zero(f):
if isclose(f, 0.0, abs_tol=1e-9):
return 0.0
else:
return f
if __name__ == '__main__':
run()
```
| 96,062 |
Provide a correct Python 3 solution for this coding contest problem.
Find common tangent lines of two circles $c1$ and $c2$.
Constraints
* $-1,000 \leq c1x, c1y, c2x, c2y \leq 1,000$
* $1 \leq c1r, c2r \leq 1,000$
* $c1$ and $c2$ are different
Input
Center coordinates ($cix$, $ciy$) and radii $cir$ of two circles $c1$ are $c2$ are given in the following format.
$c1x \; c1y \; c1r$
$c2x \; c2y \; c2r$
All input values are given in integers.
Output
Print coordinates of the tangent points on circle $c1$ based on the following rules.
* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.
The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
1 1 1
6 2 2
Output
0.6153846154 1.9230769231
1.0000000000 0.0000000000
1.4183420913 1.9082895434
1.7355040625 0.3224796874
Input
1 2 1
4 2 2
Output
0.6666666667 1.0571909584
0.6666666667 2.9428090416
2.0000000000 2.0000000000
Input
1 2 1
3 2 2
Output
0.5000000000 1.1339745962
0.5000000000 2.8660254038
Input
0 0 1
1 0 2
Output
-1.0000000000 0.0000000000
Input
0 0 1
0 0 2
Output
"Correct Solution:
```
from math import acos, atan2, cos, hypot, isclose, pi, sin
from typing import List, Tuple
def tangent_points(c1x: float, c1y: float, c1r: float,
c2x: float, c2y: float, c2r: float) -> List[Tuple[float, float]]:
c1c2 = hypot(c2x - c1x, c2y - c1y)
t0 = atan2(c2y - c1y, c2x - c1x)
ps: List[Tuple[float, float]] = []
r1r2 = c1r + c2r
if isclose(c1c2, r1r2):
ps.append((c1x + c1r * cos(t0), c1y + c1r * sin(t0)))
elif c1c2 > r1r2:
t1 = acos(r1r2 / c1c2)
ps.append((c1x + c1r * cos(t0 + t1), c1y + c1r * sin(t0 + t1)))
ps.append((c1x + c1r * cos(t0 - t1), c1y + c1r * sin(t0 - t1)))
r1r2 = c1r - c2r
if isclose(c1c2, abs(r1r2)):
if r1r2 > 0.0:
t1 = 0.0
else:
t1 = pi
ps.append((c1x + c1r * cos(t0 + t1), c1y + c1r * sin(t0 + t1)))
elif c1c2 > abs(r1r2):
if r1r2 > 0.0:
t1 = acos(r1r2 / c1c2)
else:
t1 = pi - acos(-r1r2 / c1c2)
ps.append((c1x + c1r * cos(t0 + t1), c1y + c1r * sin(t0 + t1)))
ps.append((c1x + c1r * cos(t0 - t1), c1y + c1r * sin(t0 - t1)))
return ps
if __name__ == "__main__":
c1x, c1y, c1r = map(lambda x: float(x), input().split())
c2x, c2y, c2r = map(lambda x: float(x), input().split())
ps = tangent_points(c1x, c1y, c1r, c2x, c2y, c2r)
for p in sorted(ps):
print("{:.6f} {:.6f}".format(*p))
```
| 96,063 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
where the first digits 0, 1 and 2 represent insert and get operations respectively.
Output
For each get operation, print an integer in a line.
Example
Input
7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black
Output
1
4
8
"Correct Solution:
```
q = int(input())
M = {}
for i in range(q):
query= input().split()
if query[0] == "0":
M[query[1]] = query[2]
else:
print(M[query[1]])
```
| 96,064 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
where the first digits 0, 1 and 2 represent insert and get operations respectively.
Output
For each get operation, print an integer in a line.
Example
Input
7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black
Output
1
4
8
"Correct Solution:
```
#空の辞書作成と標準入力
di = {}
for _ in range(int(input())):
line = input().split()
#リストの0番目が0なら辞書に追加する1なら出力する
if line[0] == "0":di[line[1]] = line[2]
else:print(di[line[1]])
```
| 96,065 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
where the first digits 0, 1 and 2 represent insert and get operations respectively.
Output
For each get operation, print an integer in a line.
Example
Input
7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black
Output
1
4
8
"Correct Solution:
```
M = {}
q = int(input())
for _ in range(q):
command, *list_num = input().split()
if command == "0":
# insert(key, x)
key = list_num[0]
x = int(list_num[1])
M[key] = x
elif command == "1":
# get(key)
key = list_num[0]
print(M[key])
else:
raise
```
| 96,066 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
where the first digits 0, 1 and 2 represent insert and get operations respectively.
Output
For each get operation, print an integer in a line.
Example
Input
7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black
Output
1
4
8
"Correct Solution:
```
dic = {}
for i in range(int(input())):
query = input().split()
if query[0] == '0': dic[query[1]] = query[2]
else: print(dic[query[1]])
```
| 96,067 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
where the first digits 0, 1 and 2 represent insert and get operations respectively.
Output
For each get operation, print an integer in a line.
Example
Input
7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black
Output
1
4
8
"Correct Solution:
```
import sys
n = int(input())
dic = {}
for i in range(n):
a, b, *c = sys.stdin.readline().split()
if a == '0':
dic[b] = int(c[0])
else:
print(dic[b])
```
| 96,068 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
where the first digits 0, 1 and 2 represent insert and get operations respectively.
Output
For each get operation, print an integer in a line.
Example
Input
7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black
Output
1
4
8
"Correct Solution:
```
d = {}
for _ in range(int(input())):
op, key, x = (input().split() + [''])[:3]
if op == '0':
d[key] = x
else:
print(d[key])
```
| 96,069 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
where the first digits 0, 1 and 2 represent insert and get operations respectively.
Output
For each get operation, print an integer in a line.
Example
Input
7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black
Output
1
4
8
"Correct Solution:
```
q = int(input())
dict = {}
for i in range(q):
a = input().split()
if a[0] == "0":
dict[a[1]] = a[2]
elif a[0] == "1":
print(dict[a[1]])
```
| 96,070 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
where the first digits 0, 1 and 2 represent insert and get operations respectively.
Output
For each get operation, print an integer in a line.
Example
Input
7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black
Output
1
4
8
"Correct Solution:
```
def main():
q = int(input())
d = {}
for i in range(q):
query = input()
cmd = int(query[0])
if cmd == 0:
_, k, v = query.split(' ')
v = int(v)
d[k] = v
elif cmd == 1:
_, k = query.split(' ')
v = d.get(k, None)
if v:
print(v)
if __name__ == '__main__':
main()
```
| 96,071 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
where the first digits 0, 1 and 2 represent insert and get operations respectively.
Output
For each get operation, print an integer in a line.
Example
Input
7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black
Output
1
4
8
Submitted Solution:
```
q = int(input())
M = {}
for i in range(q):
query, *inp = input().split()
key = inp[0]
# insert
if query == "0":
x = int(inp[1])
M[key] = x
# get
else:
print(M[key])
```
Yes
| 96,072 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
where the first digits 0, 1 and 2 represent insert and get operations respectively.
Output
For each get operation, print an integer in a line.
Example
Input
7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black
Output
1
4
8
Submitted Solution:
```
q = int(input())
dct = {}
for _ in range(q):
cmmd = input().split( )
if cmmd[0] == "0":
dct[cmmd[1]] = int(cmmd[2])
else:
print(dct[cmmd[1]])
```
Yes
| 96,073 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
where the first digits 0, 1 and 2 represent insert and get operations respectively.
Output
For each get operation, print an integer in a line.
Example
Input
7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black
Output
1
4
8
Submitted Solution:
```
D = {}
q = int(input())
for i in range(q):
L = input().split()
if L[0] == '0':
key, x = L[1], L[2]
D[key] = x
else:
key = L[1]
print(D[key])
```
Yes
| 96,074 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
where the first digits 0, 1 and 2 represent insert and get operations respectively.
Output
For each get operation, print an integer in a line.
Example
Input
7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black
Output
1
4
8
Submitted Solution:
```
dict = {}
q = int(input())
for i in range(q):
line = input().split()
if line[0] == "0":
dict[line[1]]=int(line[2])
elif line[0] == "1":
print(dict[line[1]])
```
Yes
| 96,075 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Tags: data structures, divide and conquer, two pointers
Correct Solution:
```
def merge(l,r):
global num
if l>=r:
return
mid=(l+r)>>1
merge(l,mid)
merge(mid+1,r)
j=mid+1
for i in range(l,mid+1):
while j<=r and arr[j]-arr[i]<t:
j+=1
num+=j-mid-1
arr[l:r+1]=sorted(arr[l:r+1])
n,t=map(int,input().split())
List=list(map(int,input().split()))
num=0
arr=[0]*(n+1)
for i in range(1,n+1):
arr[i]=arr[i-1]+List[i-1]
merge(0,n)
print(num)
```
| 96,076 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Tags: data structures, divide and conquer, two pointers
Correct Solution:
```
import sys
import bisect
input=sys.stdin.readline
class Bit:
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
def sum(self, i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self, i, x):
while i <= self.size:
self.tree[i] += x
i += i & -i
n,t=map(int,input().split())
a=list(map(int,input().split()))
pre=[0]*(n+1)
for i in range(n):
pre[i+1]=pre[i]+a[i]
pre.sort(reverse=True)
upsum=[-10**18]
for i in range(n+1):
if i==0 or pre[i]!=pre[i-1]:
upsum.append(pre[i])
upsum.sort(reverse=True)
def lower(i):
l=0;r=len(upsum)
while r-l>0:
m=(l+r)//2
if upsum[m]<=i:
r=m
else:
l=m+1
return l
ans=0
cur=0
BIT=Bit(n+2)
BIT.add(lower(0)+1,1)
for aa in a:
cur+=aa
ans+=BIT.sum(lower(cur-t))
BIT.add(lower(cur)+1,1)
print(ans)
```
| 96,077 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Tags: data structures, divide and conquer, two pointers
Correct Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 11/21/18
Fenwick Tree
prefix sum in s
j < i, s[i]-s[j] < t,
i+1 - (c = count of j that makes s[i]-s[j] >= t)
c = count of s[j] <= s[i] - t
"""
import bisect
N, T = map(int, input().split())
A = [int(x) for x in input().split()]
prefsums = [0] * (N+1)
for i in range(N):
prefsums[i+1] = A[i] + prefsums[i]
MAXNN = len(prefsums) + 1
L = [0] * MAXNN
def lsb(i):
return i & (-i)
def update(i):
while i < MAXNN:
L[i] += 1
i |= i+1
def get(i):
ans = 0
while i >= 0:
ans += L[i]
i = (i&(i+1))-1
return ans
prefsums = list(sorted(set(prefsums)))
ans = 0
update(bisect.bisect_left(prefsums, 0))
pr = 0
for i, v in enumerate(A):
pr += v
npos = bisect.bisect_right(prefsums, pr-T)
ans += i+1-get(npos-1)
k = bisect.bisect_left(prefsums, pr)
update(k)
print(ans)
```
| 96,078 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Tags: data structures, divide and conquer, two pointers
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
import math
import bisect
#for _ in range(int(input())):
from collections import Counter
#sys.setrecursionlimit(10**6)
#dp=[[-1 for i in range(n+5)]for j in range(cap+5)]
#arr= list(map(int, input().split()))
#n,m= map(int, input().split())
#arr= list(map(int, input().split()))
#for _ in range(int(input())):
import bisect
#n=int(input())
from collections import deque
#n,m= map(int, input().split())
#rr =deque(map(int, input().split()))
#for _ in range(int(input())):
#n,m=map(int, input().split())
#for _ in range(int(input())):
#n=int(input())
#arr = list(map(int, input().split()))
def up(ind,val):
while ind<=cnt+1:
bit[ind]+=1
ind+=(ind & -ind)
def bit_sum(ind):
val=0
while ind>0:
val+=bit[ind]
ind-=(ind & -ind)
return val
n,k= map(int, input().split())
arr = list(map(int, input().split()))
p=[0]*n
p[0]=arr[0]
minus=[arr[0]-k]
for i in range(1,n):
p[i]=p[i-1]+arr[i]
minus.append(p[i]-k)
minus.extend(p)
array=sorted(minus)
cnt=1
d={}
for i in array:
if i not in d:
d[i]=cnt
cnt+=1
bit=[0]*(cnt+2)
ans=0
for i in p:
var=d[i-k]
ans+=bit_sum(cnt+1)-bit_sum(var)
up(d[i],1)
if i<k:
ans+=1
print(ans)
```
| 96,079 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Tags: data structures, divide and conquer, two pointers
Correct Solution:
```
n, t = list(map(int, input().split()))
a = list(map(int, input().split()))
summ = [0]
cur = 0
for i in range(n):
cur += a[i]
summ.append(cur)
def merge(l, mid, r):
i, j = l, mid + 1
ans = 0
while i <= mid and j <= r:
if summ[i] + t > summ[j]:
ans += (mid + 1 - i)
j += 1
else:
i += 1
tmp = []
i, j = l, mid + 1
while i <= mid and j <= r:
if summ[i] <= summ[j]:
tmp.append(summ[i])
i += 1
else:
tmp.append(summ[j])
j += 1
if i <= mid:
tmp.extend(summ[i:mid + 1])
if j <= r:
tmp.extend(summ[j:r+1])
for i in range(l, r + 1):
summ[i] = tmp[i - l]
return ans
def helper(l, r):
if l == r:
return 0
mid = (l + r) // 2
ans1 = helper(l, mid)
ans2 = helper(mid + 1, r)
ans3 = merge(l, mid, r)
#print(ans1, ans2, ans3)
return ans1 + ans2 + ans3
res = helper(0, n)
print(res)
'''
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
'''
```
| 96,080 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Tags: data structures, divide and conquer, two pointers
Correct Solution:
```
maxn = 2*10**5 + 5
bit = [0]*(maxn)
def add(idx):
idx += 1
while idx < maxn:
bit[idx] += 1
idx += idx & -idx
def sm(idx):
idx += 1
tot = 0
while idx > 0:
tot += bit[idx]
idx -= idx & -idx
return tot
n,t = map(int,input().split())
a = list(map(int,input().split()))
psum = [0]*(n+1)
for i in range(n):
psum[i+1] = psum[i] + a[i]
psum.sort(reverse=True)
upsum = [-10**18]
for i in range(n+1):
if i == 0 or psum[i] != psum[i-1]:
upsum.append(psum[i])
upsum.sort(reverse = True)
def lower_bound(i):
l = 0; r = len(upsum) - 1
while l != r:
m = (l+r)//2
if upsum[m] <= i:
r = m
else:
l = m + 1
return l
ans = 0
curr = 0
add(lower_bound(0))
for i in a:
curr += i
ans += sm(lower_bound(curr-t)-1)
add(lower_bound(curr))
print(ans)
```
| 96,081 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Tags: data structures, divide and conquer, two pointers
Correct Solution:
```
def lowbit(index):
return index & (-index)
def update(index, delta=1):
while index <= size:
tree[index] += delta
index += lowbit(index)
def query(index):
res = 0
while index > 0:
res += tree[index]
index -= lowbit(index)
return res
n, t = list(map(int, input().split()))
a = list(map(int, input().split()))
#n, t = 5, 4
#a = [5, -1, 3, 4, -1]
summ_raw = [0]
summ_minus = []
cur = 0
for i in range(n):
cur += a[i]
summ_raw.append(cur)
summ_minus.append(cur - t)
summ = sorted(list(set(summ_raw + summ_minus)))
size = len(summ)
d = {}
for i in range(size):
d[summ[i]] = i + 1
#print(summ)
#print(d)
tree = [0] * (size + 1)
update(d[0])
res = 0
for i in range(1, n+1):
v = summ_raw[i]
index = d[v - t]
cur = (query(size) - query(index))
#print(tree, size, query(size), cur, v, index)
res += cur
update(d[v])
print(res)
'''
# divide and conquer, two pointers
n, t = list(map(int, input().split()))
a = list(map(int, input().split()))
summ = [0]
cur = 0
for i in range(n):
cur += a[i]
summ.append(cur)
def merge(l, mid, r):
i, j = l, mid + 1
ans = 0
while i <= mid and j <= r:
if summ[i] + t > summ[j]:
ans += (mid + 1 - i)
j += 1
else:
i += 1
tmp = []
i, j = l, mid + 1
while i <= mid and j <= r:
if summ[i] <= summ[j]:
tmp.append(summ[i])
i += 1
else:
tmp.append(summ[j])
j += 1
if i <= mid:
tmp.extend(summ[i:mid + 1])
if j <= r:
tmp.extend(summ[j:r+1])
for i in range(l, r + 1):
summ[i] = tmp[i - l]
return ans
def helper(l, r):
if l == r:
return 0
mid = (l + r) // 2
ans1 = helper(l, mid)
ans2 = helper(mid + 1, r)
ans3 = merge(l, mid, r)
#print(ans1, ans2, ans3)
return ans1 + ans2 + ans3
res = helper(0, n)
print(res)
'''
'''
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
'''
```
| 96,082 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Tags: data structures, divide and conquer, two pointers
Correct Solution:
```
import bisect
class BIT:
def __init__(self, node_size):
self._node = node_size+1
self.bit = [0]*self._node
def add(self, index, add_val):
while index < self._node:
self.bit[index] += add_val
index += index & -index
def sum(self, index):
res = 0
while index > 0:
res += self.bit[index]
index -= index & -index
return res
n,t = map(int,input().split())
a = list(map(int,input().split()))
ru = [0] * (n+1)
ans = 0
for i in range(1,n+1):
ru[i] = ru[i-1]+ a[i-1]
rus = sorted(ru)
bit = BIT(n+2)
for i in range(n+1):
ru[i] = bisect.bisect_left(rus,ru[i])
for i in range(n+1):
ind = bisect.bisect_left(rus,rus[ru[i]]-t+1)
ans += bit.sum(n+2)-bit.sum(ind)
bit.add(ru[i]+1,1)
print(ans)
```
| 96,083 |
Provide tags and a correct Python 2 solution for this coding contest problem.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Tags: data structures, divide and conquer, two pointers
Correct Solution:
```
#Run code in language PyPy2
#change input() in Python 3 become raw_input() like python2 then submit
#Add this code prefix of your code
import atexit
import io
import sys
buff = io.BytesIO()
sys.stdout = buff
@atexit.register
def write():
sys.__stdout__.write(buff.getvalue())
# code
r = raw_input
n,t = map(int,r().split())
arr = [int(x) for x in r().split()]
N = -40**14-20**14
presum =[0]
#Function
def update(Bit,x):
while(x<=n):
Bit[x]+=1
x+=(x&-x)
def get(Bit,x):
res = 0
while(x>0):
res+=Bit[x]
x-=(x&-x)
return res
#
for i in arr:
presum.append(presum[-1]+i)
fakeIndex = [N]
for i in presum:
fakeIndex.append(i)
fakeIndex.append(i-t)
fakeIndex.sort()
Indx = {}
for i,j in enumerate(fakeIndex):
#print(j,' ',i)
Indx[j] = i
n = len(fakeIndex)
Bit = [0 for i in range(0,n+1)]
ans = 0
cnt = 0
for i in presum:
#temp = get(Bit,Indx[i-t])
ans+=(cnt - get(Bit,Indx[i-t]))
update(Bit,Indx[i])
cnt+=1
print(ans)
```
| 96,084 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Submitted Solution:
```
from itertools import accumulate, chain
class Fenwick:
def __init__(self, n):
self.tree = [0] * (n + 1)
def update(self, i, val):
i += 1
while i < len(self.tree):
self.tree[i] += 1
i += (i & -i)
def get(self, i):
i += 1
total = 0
while i > 0:
total += self.tree[i]
i -= (i & -i)
return total
def solution(n, a, t):
S = [s for s in accumulate(a)]
T = set([s for s in S] + [s - t for s in S])
T = sorted(T)
T = {v: i for i, v in enumerate(T)}
fenwick = Fenwick(len(T))
total = 0
for i, v in enumerate(S):
diff = v - t
total += i - fenwick.get(T[diff])
if v < t:
total += 1
fenwick.update(T[v], 1)
return total
f = lambda: [int(c) for c in input().split()]
n, t = f()
a = f()
print(solution(n, a, t))
```
Yes
| 96,085 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Submitted Solution:
```
# https://tjkendev.github.io/procon-library/python/range_query/rsq_ruq_segment_tree_lp.html
class segmentTree():
initValue = 0
dat = []
lenTreeLeaf = -1
depthTreeList = 0
lenOriginalList = -1
func = None
funcPropagateToChild = None
lazy = None
N = -1
def load(self, l):
self.N = len(l)
self.lenOriginalList = self.N # original nodes
self.depthTreeList = (self.N - 1).bit_length() # Level of Tree
self.lenTreeLeaf = 2 ** self.depthTreeList # leaf of node, len 5 -> 2^3 = 8
self.dat = [self.initValue] * (self.lenTreeLeaf * 2)
self.lazy = [self.initValue] * (self.lenTreeLeaf * 2) # lazy propagete buffer
# Load Function
for i in range(len(l)):
self.dat[self.lenTreeLeaf - 1 + i] = l[i]
self.build()
def build(self):
for i in range(self.lenTreeLeaf - 2, -1, -1):
self.dat[i] = self.func(self.dat[2 * i + 1], self.dat[2 * i + 2])
# print("build: node", i, "child is ", self.dat[2 * i + 1], self.dat[2 * i + 2] ,"then I am ", self.dat[i])
# just wrapper, get node value and op and put it
def addValue(self, ind, value):
nodeId = (self.lenTreeLeaf - 1) + ind
self.dat[nodeId] += value
self.setValue(ind, self.dat[nodeId])
# set value to node, recalc parents NODEs
def setValue(self, ind, value):
nodeId = (self.lenTreeLeaf - 1) + ind
self.dat[nodeId] = value
while nodeId != 0:
nodeId = (nodeId - 1) // 2
self.dat[nodeId] = self.func(self.dat[nodeId * 2 + 1], self.dat[nodeId * 2 + 2])
def nodelistFromLR(self, l, r, withchild=False):
L = (l + self.lenTreeLeaf) >> 1
R = (r + self.lenTreeLeaf) >> 1
lc = 0 if l & 1 else (L & -L).bit_length()
rc = 0 if r & 1 else (R & -R).bit_length()
res = []
for i in range(self.depthTreeList + (1 if withchild else 0)):
if rc <= i:
res.append(R - 1)
if L < R and lc <= i:
res.append(L - 1)
L = L >> 1
R = R >> 1
return res
def rangeAdd(self, l, r, x):
plist = self.nodelistFromLR(l, r)
self.propagete(plist)
L = self.lenTreeLeaf + l
R = self.lenTreeLeaf + r
# print(">>before", self.lazy, L, R)
value = x
while L < R:
if R & 1:
R -= 1
# print(">>> updateR", R-1, value)
self.lazy[R - 1] = self.func(self.lazy[R - 1], value)
self.dat[R - 1] = self.func(self.dat[R - 1], value)
if L & 1:
# print(">>> updateL", L-1, value)
self.lazy[L - 1] = self.func(self.lazy[L - 1], value)
self.dat[L - 1] = self.func(self.dat[L - 1], value)
L += 1
L = L >> 1
R = R >> 1
value = self.funcRangePropagetToParent(value)
# print(">>>END cur", L, R)
# print(">>after", self.lazy)
for node in plist:
self.dat[node] = self.func(self.dat[2 * node + 1], self.dat[2 * node + 2])
def propagete(self, plist):
for nodeId in plist[::-1]:
" this function will be call from top to down"
# print("propagete", nodeId, "curlazyval =", self.lazy[nodeId])
if self.lazy[nodeId] == self.initValue:
continue
if nodeId < (self.lenTreeLeaf - 1): # if this node has childs
propageteValue = self.funcPropagateToChild(self.lazy[nodeId])
# print(" > propagate to node")
self.lazy[2 * nodeId + 1] = self.func(self.lazy[2 * nodeId + 1], propageteValue)
self.lazy[2 * nodeId + 2] = self.func(self.lazy[2 * nodeId + 2], propageteValue)
self.dat[2 * nodeId + 1] = self.func(self.dat[2 * nodeId + 1], propageteValue)
self.dat[2 * nodeId + 2] = self.func(self.dat[2 * nodeId + 2], propageteValue)
else:
# print(" > do nothing")
pass
# Feedback to myself value
# self.dat[nodeId] = self.func(self.dat[nodeId], self.lazy[nodeId])
self.lazy[nodeId] = self.initValue
def query(self, l, r):
# print("query()", l, r)
plist = self.nodelistFromLR(l, r)
self.propagete(plist)
L = self.lenTreeLeaf + l
R = self.lenTreeLeaf + r
view = []
res = self.initValue
while L < R:
if R & 1:
R -= 1
# print(">>>checkR", R-1, "value", self.dat[R-1])
res = self.func(res, self.dat[R - 1])
if L & 1:
# print(">>>checkL", L-1, "value", self.dat[L-1])
res = self.func(res, self.dat[L - 1])
L += 1
L = L >> 1
R = R >> 1
return res
def findNthValueSub(self, x, nodeId):
"""
[2, 3, 5, 7] = [0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0]
とマッピングされているセグメント木においてx番目に小さい値を得るための関数
"""
if self.dat[nodeId] < x: # このノードが要求されているよりも小さい値しか持たないとき
return (None, x - self.dat[nodeId])
if nodeId >= self.lenTreeLeaf - 1: # nodeIfがノードのときは
return (True, nodeId - (self.lenTreeLeaf - 1)) # そのindex番号を返す
resLeft = self.findNthValueSub(x, 2 * nodeId + 1) # 左側の探索を行う
if resLeft[0] != None: # もし、値が入っているならそれを返す
return (True, resLeft[1])
resRight = self.findNthValueSub(resLeft[1], 2 * nodeId + 2) # 右側の探索を行う
return resRight
def findNthValue(self, x):
return self.findNthValueSub(x, 0)[1]
class segmentTreeSum(segmentTree):
def __init__(self):
self.func = lambda x, y: x + y
self.funcPropagateToChild = lambda parentValue: parentValue >> 1
self.funcRangePropagetToParent = lambda currentValue: currentValue << 1
self.initValue = 0
class segmentTreeMin(segmentTree):
def __init__(self):
self.func = lambda x, y: min(x, y)
self.funcPropagateToChild = lambda parentValue: parentValue
self.funcRangePropagetToParent = lambda currentValue: currentValue
self.initValue = 2 * 10 ** 9
import sys
import sys
#input = sys.stdin.readline
def do():
st = segmentTreeSum()
n, t = map(int, input().split())
dat = list(map(int, input().split()))
dattotal = []
total = 0
segtreeList = [0] * (200000 + 10)
zatsu = set()
for x in dat:
total += x
dattotal.append(total)
zatsu.add(total)
zatsu = list(zatsu)
zatsu.sort()
zatsuTable = dict()
zatsuTableRev = dict()
for ind, val in enumerate(zatsu):
zatsuTable[val] = ind
zatsuTableRev[ind] = val
buf = []
for x in dattotal:
buf.append(zatsuTable[x])
segtreeList[zatsuTable[x]] += 1
st.load(segtreeList)
#print(segtreeList[:10])
from bisect import bisect_left, bisect_right
offset = 0
res = 0
#print(zatsu)
for i in range(n): # x = total from 0 to curren
#print("---------, i")
x = dattotal[i]
curvalind = zatsuTable[x]
targetval = t + offset# target val
targetind = bisect_left(zatsu, targetval)
cnt = st.query(0, targetind )
#print(i, "offset", offset, "query",curvalind, targetind+1)
#print(segtreeList[:10])
#print(x, "target=", targetval, "targetind", targetind, "cnt = ", cnt)
res += cnt
#print("cur", st.query(curvalind, curvalind+1), curvalind)
st.addValue(curvalind, -1)
#print("cur", st.query(curvalind, curvalind+1))
offset += dat[i] # for next offset
print(res)
do()
```
Yes
| 96,086 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Submitted Solution:
```
from itertools import accumulate, chain
class Fenwick:
def __init__(self, n):
self.tree = [0] * (n + 1)
def update(self, i, val):
i += 1
while i < len(self.tree):
self.tree[i] += 1
i += (i & -i)
def get(self, i):
i += 1
total = 0
while i > 0:
total += self.tree[i]
i -= (i & -i)
return total
def solution(n, a, t):
S = [s for s in accumulate(a)]
T = [[s, s - t] for s in S]
T = list(set(chain(*T)))
T.sort()
T = {v: i for i, v in enumerate(T)}
fenwick = Fenwick(len(T))
total = 0
for i, v in enumerate(S):
diff = v - t
total += i - fenwick.get(T[diff])
if v < t:
total += 1
fenwick.update(T[v], 1)
return total
f = lambda: [int(c) for c in input().split()]
n, t = f()
a = f()
print(solution(n, a, t))
```
Yes
| 96,087 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Submitted Solution:
```
n,t=map(int,input().split())
a=list(map(int,input().split()))
bit=[0 for i in range(n+2)]
def qq(i):
ans=0
i=i+1
while i>0:
ans+=bit[i]
i-=i&-i
return(ans)
def u(i):
i+=1
while i<=n+1:
bit[i]+=1
i+=i&-i
q=[]
c=[0]
for i in range(n):
c.append(c[-1]+a[i])
q.append((i+1,t+c[i]))
c=[(c[i],i) for i in range(n+1)]
c.sort()
q.sort(key=lambda x:x[1])
ans=0
i=0
j=0
while j<len(q):
l,x=q[j]
while i<=n and c[i][0]<x:
u(c[i][1])
i+=1
ans+=qq(n)-qq(l-1)
j+=1
print(ans)
```
Yes
| 96,088 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Submitted Solution:
```
n,t=list(map(int,input().split()))
b=list(map(int,input().split()))
def segementsum(a):return a[0] if len(a)==1 else 0 if len(a)==0 else segementsum(a[:int(len(a)/2)])+segementsum(a[int(len(a)/2):])
sol=0
sum=[segementsum(b[:i]) for i in range(len(b)+1)]
sum=sum[1:]
#print(sum)
for i in range(len(b)):
for j in range(i+1,len(b)):
#print(sum[j]-sum[i],i,j)
if sum[j]-sum[i]<t:sol+=1
print(sol)
```
No
| 96,089 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Submitted Solution:
```
#code force
#divide and conquer
#Petya and Array
get_nums_seq = input().split(" ") # get the number in the seq , the upper bound and the seq ----a lst
def p_sum(nums_seq):
"""
Input : a list
nums --- number of items
ub ---upper bound
seq --- the sequence
Output: an int
return the number of valid partial sums
"""
nums = int(nums_seq[0]) #arrange info from the input
ub = int(nums_seq[1])
seq = []
for num in nums_seq[2:]: # turn all numbers in sequence into int
seq.append(int(num))
def add_recur(seq): #for adding partial sums
"""
input: a sequence
output: sum of the sequence
"""
seq_l = len(seq)
if seq_l == 1:
return seq[0]
else:
return seq[seq_l-1] + add_recur(seq[0:seq_l-1])
count = 0
for i in range(len(seq)):
if i == len(seq)-1:
if seq[-1] < ub:
count += 1
break
for ii in range(i+1,len(seq)+1):
part_sum = add_recur(seq[i:ii])
if part_sum < ub:
count += 1
return count
p_sum(get_nums_seq)
```
No
| 96,090 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Submitted Solution:
```
n,t=list(map(int,input().split()))
b=list(map(int,input().split()))
def segementsum(a):return a[0] if len(a)==1 else 0 if len(a)==0 else segementsum(a[:int(len(a)/2)])+segementsum(a[int(len(a)/2):])
sol=0
sum=[segementsum(b[0:i]) for i in range(len(b)+1)]
for i in range(len(b)):
for j in range(i+1,len(b)):
if sum[j]-sum[i]<t:sol+=1
print(sol)
```
No
| 96,091 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.
Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.
More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t.
Input
The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}).
The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.
Output
Print the number of segments in Petya's array with the sum of elements less than t.
Examples
Input
5 4
5 -1 3 4 -1
Output
5
Input
3 0
-1 2 -3
Output
4
Input
4 -1
-2 1 -2 3
Output
3
Note
In the first example the following segments have sum less than 4:
* [2, 2], sum of elements is -1
* [2, 3], sum of elements is 2
* [3, 3], sum of elements is 3
* [4, 5], sum of elements is 3
* [5, 5], sum of elements is -1
Submitted Solution:
```
import bisect
class BIT:
def __init__(self, node_size):
self._node = node_size+1
self.bit = [0]*self._node
def add(self, index, add_val):
while index < self._node:
self.bit[index] += add_val
index += index & -index
def sum(self, index):
res = 0
while index > 0:
res += self.bit[index]
index -= index & -index
return res
n,t = map(int,input().split())
a = list(map(int,input().split()))
ru = [0] * (n+1)
ans = 0
for i in range(1,n+1):
ru[i] = ru[i-1]+ a[i-1]
rus = sorted(ru)
bit = BIT(n+2)
for i in range(n+1):
ru[i] = bisect.bisect_left(rus,ru[i])
for i in range(n+1):
ind = bisect.bisect_left(rus,rus[ru[i]]-t+1)
indi = bisect.bisect_left(rus,abs(rus[ru[i]])+abs(t))
ans += abs(bit.sum(indi)-bit.sum(ind))
bit.add(ru[i]+1,1)
print(ans)
```
No
| 96,092 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of h_i cubes, so it has height h_i.
Let's define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make tower's height equal to H. Cost of one "slice" equals to the total number of removed cubes from all towers.
Let's name slice as good one if its cost is lower or equal to k (k ≥ n).
<image>
Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n ≤ k ≤ 10^9) — the number of towers and the restriction on slices, respectively.
The second line contains n space separated integers h_1, h_2, ..., h_n (1 ≤ h_i ≤ 2 ⋅ 10^5) — the initial heights of towers.
Output
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
Examples
Input
5 5
3 1 2 2 4
Output
2
Input
4 5
2 3 4 5
Output
2
Note
In the first example it's optimal to make 2 slices. The first slice is on height 2 (its cost is 3), and the second one is on height 1 (its cost is 4).
Tags: greedy
Correct Solution:
```
n, k = map(int, input().split())
h = list(map(int, input().split()))
h.sort(reverse=True)
levels = []
prev = h[0]
count = 1
for x in h[1:]:
if x != prev:
for _ in range(prev - x):
levels.append(count)
prev = x
count += 1
if len(levels) == 0:
print(0)
exit(0)
s = 0
count = 1
for x in levels:
s += x
if s > k:
count += 1
s = x
print(count)
```
| 96,093 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of h_i cubes, so it has height h_i.
Let's define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make tower's height equal to H. Cost of one "slice" equals to the total number of removed cubes from all towers.
Let's name slice as good one if its cost is lower or equal to k (k ≥ n).
<image>
Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n ≤ k ≤ 10^9) — the number of towers and the restriction on slices, respectively.
The second line contains n space separated integers h_1, h_2, ..., h_n (1 ≤ h_i ≤ 2 ⋅ 10^5) — the initial heights of towers.
Output
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
Examples
Input
5 5
3 1 2 2 4
Output
2
Input
4 5
2 3 4 5
Output
2
Note
In the first example it's optimal to make 2 slices. The first slice is on height 2 (its cost is 3), and the second one is on height 1 (its cost is 4).
Tags: greedy
Correct Solution:
```
n, k = map(int, input().split())
A = list(map(int, input().split()))
A.sort(reverse=True)
ans = 0
g = A[-1]
h = A[0]
p = 0
i = 1
c = 0
l = 0
while h > g and i < n:
if A[i] == A[p]:
p += 1
i += 1
continue
for j in range(A[p] - A[i]):
c += p+1
l += 1
if c > k:
ans += 1
h -= l-1
c = p+1
l = 0
if h <= g:
break
p = i
i += 1
if h > g:
ans += 1
print(ans)
```
| 96,094 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of h_i cubes, so it has height h_i.
Let's define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make tower's height equal to H. Cost of one "slice" equals to the total number of removed cubes from all towers.
Let's name slice as good one if its cost is lower or equal to k (k ≥ n).
<image>
Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n ≤ k ≤ 10^9) — the number of towers and the restriction on slices, respectively.
The second line contains n space separated integers h_1, h_2, ..., h_n (1 ≤ h_i ≤ 2 ⋅ 10^5) — the initial heights of towers.
Output
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
Examples
Input
5 5
3 1 2 2 4
Output
2
Input
4 5
2 3 4 5
Output
2
Note
In the first example it's optimal to make 2 slices. The first slice is on height 2 (its cost is 3), and the second one is on height 1 (its cost is 4).
Tags: greedy
Correct Solution:
```
n,k=list(map(int,input().split()))
h=list(map(int,input().split()))
m=h[0]
m1=h[0]
for i in h:
m=max(m,i)
m1=min(m1,i)
if h==[m]*n:
print(0)
else:
a=[0]*m
for i in h:
a[i-1]+=1
b=[0]*m
c=0
for i in range(m-1,-1,-1):
c+=a[i]
b[i]=c
d=0
e=0
for i in range(m-1,-1,-1):
e+=b[i]
if i+1<m1:
break
if e>k or i+1==m1:
e=b[i]
d+=1
print(d)
```
| 96,095 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of h_i cubes, so it has height h_i.
Let's define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make tower's height equal to H. Cost of one "slice" equals to the total number of removed cubes from all towers.
Let's name slice as good one if its cost is lower or equal to k (k ≥ n).
<image>
Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n ≤ k ≤ 10^9) — the number of towers and the restriction on slices, respectively.
The second line contains n space separated integers h_1, h_2, ..., h_n (1 ≤ h_i ≤ 2 ⋅ 10^5) — the initial heights of towers.
Output
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
Examples
Input
5 5
3 1 2 2 4
Output
2
Input
4 5
2 3 4 5
Output
2
Note
In the first example it's optimal to make 2 slices. The first slice is on height 2 (its cost is 3), and the second one is on height 1 (its cost is 4).
Tags: greedy
Correct Solution:
```
n , k = map(int,input().split())
ar = list(map(int,input().split()))
N = int(2e5 + 10)
cnt = [0 for _ in range(N)]
for i in ar:
cnt[i] += 1
# print(cnt[1:max(ar) + 1])
for i in range( N-2 , 0 , -1 ):
cnt[i] += cnt[i+1]
cnt[0] = 0
i = N-1
_sum = 0
ans = 0
while i >= 1 :
if cnt[i] % n == 0 and cnt[i]!=0:
if _sum!=0 : ans += 1
break
if _sum + cnt[i] <= k:
_sum += cnt[i]
else :
ans += 1
# print(_sum , i)
_sum = cnt[i]
i -= 1
# print(cnt[1:max(ar) + 1])
print(ans)
```
| 96,096 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of h_i cubes, so it has height h_i.
Let's define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make tower's height equal to H. Cost of one "slice" equals to the total number of removed cubes from all towers.
Let's name slice as good one if its cost is lower or equal to k (k ≥ n).
<image>
Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n ≤ k ≤ 10^9) — the number of towers and the restriction on slices, respectively.
The second line contains n space separated integers h_1, h_2, ..., h_n (1 ≤ h_i ≤ 2 ⋅ 10^5) — the initial heights of towers.
Output
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
Examples
Input
5 5
3 1 2 2 4
Output
2
Input
4 5
2 3 4 5
Output
2
Note
In the first example it's optimal to make 2 slices. The first slice is on height 2 (its cost is 3), and the second one is on height 1 (its cost is 4).
Tags: greedy
Correct Solution:
```
if __name__ == "__main__":
numOfTowers, numOfOperation = map(int, input().split())
towerheights = list(map(int, input().split()))
towerheights.sort(reverse=True)
# print(towerheights)
# [4, 3, 2, 2, 1]
counter = 0
lowerheight = towerheights[-1]
higherheight = towerheights[0]
nextheightindex = 1
minNumOfgoodSlices = 0
while higherheight != lowerheight:
while higherheight == towerheights[nextheightindex]:
nextheightindex += 1
if counter + nextheightindex > numOfOperation:
minNumOfgoodSlices += 1
counter = nextheightindex
else:
counter += nextheightindex
higherheight -= 1
if counter > 0:
minNumOfgoodSlices += 1
print(minNumOfgoodSlices)
# input('enter to exit')
```
| 96,097 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of h_i cubes, so it has height h_i.
Let's define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make tower's height equal to H. Cost of one "slice" equals to the total number of removed cubes from all towers.
Let's name slice as good one if its cost is lower or equal to k (k ≥ n).
<image>
Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n ≤ k ≤ 10^9) — the number of towers and the restriction on slices, respectively.
The second line contains n space separated integers h_1, h_2, ..., h_n (1 ≤ h_i ≤ 2 ⋅ 10^5) — the initial heights of towers.
Output
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
Examples
Input
5 5
3 1 2 2 4
Output
2
Input
4 5
2 3 4 5
Output
2
Note
In the first example it's optimal to make 2 slices. The first slice is on height 2 (its cost is 3), and the second one is on height 1 (its cost is 4).
Tags: greedy
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
MOD=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
n,k=value()
a=array()
C=Counter(a)
a=sorted(set(a))
level=[]
# print(*a)
over=0
for i in range(min(a),max(a)+1):
level.append(n-over)
over+=C[i]
# print(level)
level=level[::-1]
level=level[:-1]
# print(level)
ans=0
cur=0
for i in level:
if(cur+i>k):
cur=0
ans+=1
cur+=i
ans+=cur>0
print(ans)
```
| 96,098 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of h_i cubes, so it has height h_i.
Let's define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make tower's height equal to H. Cost of one "slice" equals to the total number of removed cubes from all towers.
Let's name slice as good one if its cost is lower or equal to k (k ≥ n).
<image>
Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n ≤ k ≤ 10^9) — the number of towers and the restriction on slices, respectively.
The second line contains n space separated integers h_1, h_2, ..., h_n (1 ≤ h_i ≤ 2 ⋅ 10^5) — the initial heights of towers.
Output
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
Examples
Input
5 5
3 1 2 2 4
Output
2
Input
4 5
2 3 4 5
Output
2
Note
In the first example it's optimal to make 2 slices. The first slice is on height 2 (its cost is 3), and the second one is on height 1 (its cost is 4).
Tags: greedy
Correct Solution:
```
from sys import stdin,stdout
def main():
n,k = map(int,stdin.readline().split())
a = list(map(int,stdin.readline().split()))
h_cnt = [0 for i in range(200005) ]
mn,mx = 200000, 1
for i in range(n):
h_cnt[ a[i] ] += 1
mx = max(mx,a[i])
tmp = mx
while tmp:
if h_cnt[ tmp ] == n:
break
h_cnt [ tmp ] += h_cnt[ tmp + 1 ]
tmp -= 1
tmp = 0
ans = 0
while mx:
if h_cnt[ mx ] == n:
break
if h_cnt[ mx ] + tmp > k:
tmp = 0
ans += 1
else:
tmp += h_cnt[ mx ]
mx -= 1
if tmp:
ans += 1
stdout.write( '%d' % ans )
del n,k,a,h_cnt
main()
```
| 96,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.