text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8
Submitted Solution:
```
import numpy as np
N=int(input())
pos_mat=np.zeros((N,2))
for i in range(N):
buf=input().split()
pos_mat[i,0]=int(buf[0])
pos_mat[i,1]=int(buf[1])
minCost_arr=np.array([float("inf") for _ in range(N)])
used_arr=np.zeros(N, dtype=bool)
minCost_arr[0]=0
totalCost=0
while np.sum(used_arr)<N:
idx=np.arange(N)[~used_arr]
u=idx[np.argmin(minCost_arr[idx])]
totalCost+=minCost_arr[u]
used_arr[u]=True
for v in range(N):
edgeCost=min(abs(pos_mat[u, 0]-pos_mat[v,0]), abs(pos_mat[u, 1]-pos_mat[v,1]))
minCost_arr[v]=min(minCost_arr[v], edgeCost)
print(int(totalCost))
```
No
| 7,400 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8
Submitted Solution:
```
import sys
#import time
import copy
#from collections import deque, Counter, defaultdict
#from fractions import gcd
#import bisect
#import heapq
#import time
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
inf = 10**18
MOD = 1000000007
ri = lambda : int(input())
rs = lambda : input().strip()
rl = lambda : list(map(int, input().split()))
class UnionFind():
def __init__(self, n):
self.n = n
self.root = [-1]*(n+1)
self.rnk = [0]*(n+1)
# ノードxのrootノードを見つける
def find(self, x):
if(self.root[x] < 0):
return x
else:
self.root[x] = self.find(self.root[x])
return self.root[x]
# 木の併合、入力は併合したい各ノード
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if(x == y):
return
elif(self.rnk[x] > self.rnk[y]):
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
if(self.rnk[x] == self.rnk[y]):
self.rnk[y] += 1
# xとyが同じグループに属するか判断
def same(self, x, y):
return self.find(x) == self.find(y)
# ノードxが属する木のサイズを返す
def size(self, x):
return -self.root[self.find(x)]
def kruskal(v, edge):
edge.sort(key=lambda x: x[2])
res=0
uf = UnionFind(v)
for e in edge:
if uf.same(e[0], e[1]):
continue
uf.unite(e[0], e[1])
res+=e[2]
return res
n = ri()
d1=[rl()+[i] for i in range(n)]
d2=copy.deepcopy(d1)
d1.sort(key=lambda x: x[0])
d2.sort(key=lambda x: x[1])
edge=[]
for i in range(n-1):
edge.append(( d1[i+1][2], d1[i][2],d1[i+1][0]-d1[i][0]))
edge.append(( d2[i+1][2], d2[i][2],d2[i+1][1]-d2[i][1]))
edge.sort(key=lambda x: x[2])
res=0
uf = UnionFind(n)
for e in edge:
if uf.same(e[0], e[1]):
continue
uf.unite(e[0], e[1])
res+=e[2]
print(res)
```
No
| 7,401 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
"Correct Solution:
```
n,m = map(int,input().split())
INF = 10**18
d = [[INF]*n for _ in range(n)]
nd = [[INF]*n for _ in range(n)]
for i in range(n):
d[i][i] = 0
nd[i][i] = 0
for _ in range(m):
a,b,c = map(int,input().split())
a -= 1
b -= 1
d[a][b] = c
d[b][a] = c
nd[a][b] = c
nd[b][a] = c
for k in range(n):
for i in range(n):
for j in range(n):
nd[i][j] = min(nd[i][j], nd[i][k]+nd[k][j])
cnt = 0
for i in range(n):
for j in range(n):
if d[i][j] == INF: continue
if nd[i][j] < d[i][j]: cnt += 1
print(cnt//2)
```
| 7,402 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
"Correct Solution:
```
INF = float("inf")
def WarshallFloyd(M):
N = len(M)
for k in range(N):
for j in range(N):
for i in range(N):
M[i][j] = min(M[i][j], M[i][k] + M[k][j])
return M
N, M, *ABC = map(int, open(0).read().split())
E = [[INF] * (N + 1) for _ in range(N + 1)]
for a, b, c in zip(*[iter(ABC)] * 3):
E[a][b] = c
E[b][a] = c
D = WarshallFloyd(E)
print(sum(D[a][b] < c for a, b, c in zip(*[iter(ABC)] * 3)))
```
| 7,403 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
"Correct Solution:
```
N, M = list(map(int, input().split()))
abc = [list(map(int, input().split())) for _ in range(M)]
inf = 1000000
L = [[0] * N for _ in range(N)]
C = [[inf] * N for _ in range(N)]
for i in range(M):
a, b, c = abc[i]
a -= 1
b -= 1
C[a][b] = c
C[b][a] = c
for i in range(N):
C[i][i] = 0
for k in range(N):
for i in range(N):
for j in range(N):
if C[i][j] > C[i][k] + C[k][j]:
C[i][j] = C[i][k] + C[k][j]
L[i][j] = 1
n = 0
for i in range(N):
for j in range(N):
if L[i][j] == 1:
n += 1
print(M - ((N * (N - 1) // 2) - (n // 2)))
```
| 7,404 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
"Correct Solution:
```
N, M = map(int, input().split())
inf = 10**6
abc = []
d = [[inf]*N for i in range(N)]
for i in range(M):
a, b, c = map(int, input().split())
d[a-1][b-1] = c
d[b-1][a-1] = c
abc.append((a-1,b-1,c))
for k in range(N):
for i in range(N):
for j in range(N):
d[i][j] = min(d[i][k]+d[k][j], d[i][j])
ans = 0
for i in range(M):
a, b, c = abc[i]
if d[a][b] < inf and d[a][b] < c:
ans += 1
print(ans)
```
| 7,405 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
"Correct Solution:
```
def warshall_floyd(d):
for k in range(N):
for i in range(N):
for j in range(N):
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
return d
N, M = map(int, input().split())
d = [[float('inf') for i in range(N)] for i in range(N)]
edges = []
for i in range(M):
a,b,c = map(int, input().split())
a -= 1
b -= 1
d[a][b] = c
d[b][a] = c
edges.append([a,b,c])
warshall_floyd(d)
# 与えられた頂点間の辺の距離が求めた最短距離より大きければ
# その辺は使われない
cnt = 0
for edge in edges:
if d[edge[0]][edge[1]] != edge[2]:
cnt += 1
print(cnt)
```
| 7,406 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
"Correct Solution:
```
n,m=[int(x) for x in input().split()]
path=[]
d=[[float("inf") for _ in [0]*n] for _2 in [0]*n]
for _ in [0]*m:
a,b,c=[int(x) for x in input().split()]
path.append((a-1,b-1,c))
d[a-1][b-1]=d[b-1][a-1]=c
from itertools import product
for k,i,j in product(range(n),range(n),range(n)):
if d[i][j]>d[i][k]+d[k][j]:
d[i][j]=d[i][k]+d[k][j]
ans=0
for a,b,c in path:
if d[a][b]!=c:
ans+=1
print(ans)
```
| 7,407 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
"Correct Solution:
```
# -*- coding: utf-8 -*-
def inpl(): return map(int, input().split())
N, M = inpl()
INF = float("inf")
G = [[INF]*(N) for _ in range(N)]
E = []
for _ in range(M):
a, b, c = inpl()
G[a-1][b-1] = c
G[b-1][a-1] = c
E.append([a-1, b-1, c])
for k in range(N):
for i in range(N):
for j in range(N):
G[i][j] = min(G[i][j], G[i][k] + G[k][j])
print(sum([G[a][b] < c for a, b, c in E]))
```
| 7,408 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
"Correct Solution:
```
n,m=map(int,input().split())
inf=float("inf")
data=[[inf]*(n+1) for i in range(n+1)]
for i in range(1,n+1):
data[i][i]=0
lst=[]
for u in range(m):
a,b,c=map(int,input().split())
data[a][b]=c
data[b][a]=c
lst.append([a,b,c])
for k in range(1,n+1):
for i in range(1,n+1):
for j in range(1,n+1):
data[i][j]=min(data[i][j],data[i][k]+data[k][j])
ans=0
for u in lst:
a,b,c=u
if data[a][b]!=c:
ans+=1
print(ans)
```
| 7,409 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
Submitted Solution:
```
N,M=[int(i) for i in input().split()]
edges=[[2**60 for i in range(N)] for j in range(N)]
for i in range(M):
a,b,c=[int(i) for i in input().split()]
a-=1
b-=1
edges[a][b]=edges[b][a]=c
mini=[[edges[i][j] for i in range(N)] for j in range(N)]
for k in range(N):
for i in range(N):
for j in range(N):
mini[i][j]=min(mini[i][j],mini[i][k]+mini[k][j])
res=0
for r in range(N):
for l in range(r):
#print(l,".",r,"->",edges[l][r],mini[l][r])
if edges[l][r] != 2**60 and mini[l][r]<edges[l][r]:
res+=1
print(res)
```
Yes
| 7,410 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
Submitted Solution:
```
from copy import deepcopy
N, M = map(int, input().split())
INF = 10000000
D = [[INF for _ in range(N)] for _ in range(N)]
for _ in range(M):
a, b, c = map(int, input().split())
D[a-1][b-1] = c
D[b-1][a-1] = c
F = deepcopy(D)
for k in range(N):
for i in range(N):
for j in range(N):
F[i][j] = min(F[i][j], F[i][k]+F[k][j])
a = 0
for i in range(N):
for j in range(N):
if D[i][j] == F[i][j]:
a += 1
a //= 2
print(M-a)
```
Yes
| 7,411 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
Submitted Solution:
```
n,m = map(int,input().split())
INF = 10**18
d = [[INF]*n for _ in range(n)]
for i in range(n): d[i][i] = 0
A = [0]*m
B = [0]*m
C = [0]*m
for i in range(m):
a,b,c = map(int,input().split())
a -= 1
b -= 1
A[i] = a
B[i] = b
C[i] = c
d[a][b] = c
d[b][a] = c
for k in range(n):
for i in range(n):
for j in range(n):
d[i][j] = min(d[i][j], d[i][k]+d[k][j])
ans = 0
for i in range(m):
if d[A[i]][B[i]] < C[i]: ans += 1
print(ans)
```
Yes
| 7,412 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
Submitted Solution:
```
def warshall_floyd(d,n):
#d[i][j]: iからjへの最短距離
for k in range(n):
for i in range(n):
for j in range(n):
d[i][j] = min(d[i][j],d[i][k] + d[k][j])
return d
N,M = [int(x) for x in input().split()]
INF = float('inf')
edges = []
d = [[INF]*N for _ in range(N)]
for _ in range(M):
a,b,c = [int(x) for x in input().split()]
a-=1
b-=1
d[a][b]=c
d[b][a]=c
edges.append([a,b,c])
warshall_floyd(d,N)
cnt = 0
for e in edges:
if(d[e[0]][e[1]]!=e[2]):
cnt+=1
print(cnt)
```
Yes
| 7,413 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
Submitted Solution:
```
inf = 10**10
N, M = map(int, input().split())
g = [[0 for _ in range(N)] for _ in range(N)]
for _ in range(M):
a, b, c = map(int, input().split())
g[a-1][b-1] = c
g[b-1][a-1] = c
g2 = [[inf if not i else i for i in j] for j in g]
for i in range(N):
g2[i][i] = 0
ans = 0
for i in range(N):
for j in range(N):
if g[i][j]:
f = 1
else:
f = 0
for k in range(N):
if f == 1 and g2[i][j] > g2[i][k] + g2[k][j]:
ans += 1
f = 0
g2[i][j] = min(g2[i][j],g2[i][k]+g2[k][j])
g2[j][i] = min(g2[i][j],g2[i][k]+g2[k][j])
print(ans)
```
No
| 7,414 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
Submitted Solution:
```
N,M=map(int,input().split())
import heapq
def dijkstra_heap(s):
#始点sから各頂点への最短距離
dist=[float("inf")]*size_v
used=[False]*size_v
prev=[-1]*size_v
dist[s]=0
used[s]=True
hq_edge=[]
for v,w,i in graph[s]:
heapq.heappush(hq_edge,(w,v,i))
while hq_edge:
min_w,min_v,ei=heapq.heappop(hq_edge)
#まだ使われてない頂点の中から最小の距離のものを探す
if used[min_v]:
continue
dist[min_v]=min_w
used[min_v]=True
prev[min_v]=ei
for v,w,ei2 in graph[min_v]:
if not used[v]:
heapq.heappush(hq_edge,(min_w+w,v,ei2))
#return dist
return prev
graph=[[] for _ in range(N+1)]
for i in range(M):
a,b,c=map(int,input().split())
graph[a].append((b,c,i))
graph[b].append((a,c,i))
#print(graph)
size_v=N+1
answer_set=set()
for i in range(1,N+1):
prev=dijkstra_heap(i)
#print(prev)
for j in range(1,N+1):
if i==j:
continue
answer_set.add(prev[j])
#print(answer_set)
print(M-len(answer_set))
```
No
| 7,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
Submitted Solution:
```
import sys
input = sys.stdin.readline
n,m=map(int,input().split())
d=[[100000]*n for _ in range(n)]
a=[0]*m
b=[0]*m
c=[0]*m
for i in range(m):
a0,b0,c0=map(int,input().split())
a[i]=a0-1
b[i]=b0-1
c[i]=c0
d[a0-1][b0-1]=c0
d[b0-1][a0-1]=c0
for i in range(n):
d[i][i]=0
for k in range(n):
for i in range(n):
for j in range(n):
d[i][j]=min(d[i][j],d[i][k]+d[k][j])
count=0
for edge in range(m):
flag=False
for j in range(n):
for k in range(n):
if d[j][a[edge]]+c[edge]==d[j][b[edge]]:
flag=True
break
if flag:
break
else:
count+=1
print(count)
```
No
| 7,416 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A connected graph is a graph where there is a path between every pair of different vertices.
Find the number of the edges that are not contained in any shortest path between any pair of different vertices.
Constraints
* 2≤N≤100
* N-1≤M≤min(N(N-1)/2,1000)
* 1≤a_i,b_i≤N
* 1≤c_i≤1000
* c_i is an integer.
* The given graph contains neither self-loops nor double edges.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Output
Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.
Examples
Input
3 3
1 2 1
1 3 1
2 3 3
Output
1
Input
3 2
1 2 1
2 3 1
Output
0
Submitted Solution:
```
n,m = map(int,input().split())
l = [list(map(int,input().split())) for _ in range(m)]
dp = [[0 for _ in range(n)] for _ in range(n)]
INF = 10**18
for i in range(n):
for j in range(n):
if i!=j:
dp[i][j] = INF
for a,b,t in l:
dp[a-1][b-1] = t
dp[b-1][a-1] = t
#print(dp)
#最短リスト
for c in range(n):
for f in range(n):
for la in range(n):
dp[f][la] = min(dp[f][la] , dp[f][c] + dp[c][la])
#各辺が何かしらの最短ルートに含まれているか
ans = 0
for a, b, t in l:
cou = 0
for j in range(n):
for k in range(n):
#jからkの最短ルートにa,bが入ってるいるか
if dp[j][k] != dp[j][a-1] + t + dp[b-1][k]:
cou += 1
if cou==n**2:
ans += 1
print(ans)
```
No
| 7,417 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice, Bob and Charlie are playing Card Game for Three, as below:
* At first, each of the three players has a deck consisting of some number of cards. Alice's deck has N cards, Bob's deck has M cards, and Charlie's deck has K cards. Each card has a letter `a`, `b` or `c` written on it. The orders of the cards in the decks cannot be rearranged.
* The players take turns. Alice goes first.
* If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says `a`, Alice takes the next turn.)
* If the current player's deck is empty, the game ends and the current player wins the game.
There are 3^{N+M+K} possible patters of the three player's initial decks. Among these patterns, how many will lead to Alice's victory?
Since the answer can be large, print the count modulo 1\,000\,000\,007 (=10^9+7).
Constraints
* 1 \leq N \leq 3×10^5
* 1 \leq M \leq 3×10^5
* 1 \leq K \leq 3×10^5
Input
The input is given from Standard Input in the following format:
N M K
Output
Print the answer modulo 1\,000\,000\,007 (=10^9+7).
Examples
Input
1 1 1
Output
17
Input
4 2 2
Output
1227
Input
1000 1000 1000
Output
261790852
Submitted Solution:
```
mod=int(1E9+7)
JS=[1]
for i in range(1,4000):
JS.append(JS[-1]*i%mod)
Cs=lambda x,y:js(x)*inv(js(y))*inv(js(x-y))%mod
inv =lambda x:pow(x,mod-2,mod)
js=lambda x:JS[x]
#while True:
A,B,C=map(int,input().split())
A-=1;B+=1;C+=1;
ans=0
for x in range(1,B+1):
for y in range(1,C+1):
ans+=Cs(A+B-x+C-y,A)*Cs(B-x+C-y,B-x)*pow(3,x-1+y-1,mod)%mod
ans%=mod
print(ans)
```
No
| 7,418 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice, Bob and Charlie are playing Card Game for Three, as below:
* At first, each of the three players has a deck consisting of some number of cards. Alice's deck has N cards, Bob's deck has M cards, and Charlie's deck has K cards. Each card has a letter `a`, `b` or `c` written on it. The orders of the cards in the decks cannot be rearranged.
* The players take turns. Alice goes first.
* If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says `a`, Alice takes the next turn.)
* If the current player's deck is empty, the game ends and the current player wins the game.
There are 3^{N+M+K} possible patters of the three player's initial decks. Among these patterns, how many will lead to Alice's victory?
Since the answer can be large, print the count modulo 1\,000\,000\,007 (=10^9+7).
Constraints
* 1 \leq N \leq 3×10^5
* 1 \leq M \leq 3×10^5
* 1 \leq K \leq 3×10^5
Input
The input is given from Standard Input in the following format:
N M K
Output
Print the answer modulo 1\,000\,000\,007 (=10^9+7).
Examples
Input
1 1 1
Output
17
Input
4 2 2
Output
1227
Input
1000 1000 1000
Output
261790852
Submitted Solution:
```
#include <bits/stdc++.h>
using namespace std;
long long mod_pow(long long base, long long exp) {
if (exp == 0) return 1;
if (exp & 1)
return (mod_pow(base, exp - 1) * base) % 1000000007;
else
return mod_pow((base * base) % 1000000007, exp / 2);
}
long long fac[3 * 1000 + 1];
long long fac_inv[3 * 1000 + 1];
long long C(long long n, long long k) {
if (k < 0 || n < k) return 0;
long long num = fac[n];
long long den = (fac_inv[n - k] * fac_inv[k]) % 1000000007;
return (num * den) % 1000000007;
}
int main() {
fac[0] = 1;
for (long long n = 1; n <= 3 * 1000; n++)
fac[n] = (fac[n - 1] * n) % 1000000007;
fac_inv[3 * 1000] = mod_pow(fac[3 * 1000], 1000000007 - 2);
for (long long n = 3 * 1000 - 1; n >= 0; n--)
fac_inv[n] = (fac_inv[n + 1] * (n + 1)) % 1000000007;
long long a, b, c;
cin >> a >> b >> c;
a++;
if (!(b > c)) {
b = b ^ c;
c = b ^ c;
b = b ^ c;
}
long long ans = 0;
long long sum = 1;
long long pull = 0;
for (long long n = a; n <= a + b + c; n++) {
long long sub = 0;
sub = (sub + sum - pull) % 1000000007;
sub = (sub * C(n - 2, a - 2)) % 1000000007;
sub = (sub * mod_pow(3, a + b + c - n)) % 1000000007;
ans = (ans + sub) % 1000000007;
sum = (2 * sum - C(n - a, c)) % 1000000007;
pull = (2 * pull + C(n - a, n - a - b)) % 1000000007;
}
cout << (ans + 1000000007) % 1000000007 << endl;
return 0;
}
```
No
| 7,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice, Bob and Charlie are playing Card Game for Three, as below:
* At first, each of the three players has a deck consisting of some number of cards. Alice's deck has N cards, Bob's deck has M cards, and Charlie's deck has K cards. Each card has a letter `a`, `b` or `c` written on it. The orders of the cards in the decks cannot be rearranged.
* The players take turns. Alice goes first.
* If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says `a`, Alice takes the next turn.)
* If the current player's deck is empty, the game ends and the current player wins the game.
There are 3^{N+M+K} possible patters of the three player's initial decks. Among these patterns, how many will lead to Alice's victory?
Since the answer can be large, print the count modulo 1\,000\,000\,007 (=10^9+7).
Constraints
* 1 \leq N \leq 3×10^5
* 1 \leq M \leq 3×10^5
* 1 \leq K \leq 3×10^5
Input
The input is given from Standard Input in the following format:
N M K
Output
Print the answer modulo 1\,000\,000\,007 (=10^9+7).
Examples
Input
1 1 1
Output
17
Input
4 2 2
Output
1227
Input
1000 1000 1000
Output
261790852
Submitted Solution:
```
mod=int(1E9+7)
JS=[1]
for i in range(1,5000):
JS.append(JS[-1]*i%mod)
Cs=lambda x,y:js(x)*inv(js(y))*inv(js(x-y))%mod
inv =lambda x:pow(x,mod-2,mod)
js=lambda x:JS[x]
#while True:
A,B,C=map(int,input().split())
A-=1;B+=1;C+=1;
ans=0
for x in range(1,B+1):
for y in range(1,C+1):
ans+=Cs(A+B-x+C-y,A)*Cs(B-x+C-y,B-x)*pow(3,x-1+y-1,mod)%mod
ans%=mod
print(ans)
```
No
| 7,420 |
Provide a correct Python 3 solution for this coding contest problem.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
"Correct Solution:
```
def x(p0, p1):
d = abs(p0 - p1)
if d > 2:
return []
elif d == 2:
return [(p0 + p1) / 2]
else:
m = (p0 + p1) / 2
v = m - p0
w = complex(v.imag, -v.real)
l = abs(w)
h = (1 - l ** 2) ** .5 * w / l
return [m + h, m - h]
for e in iter(input, '0'):
n = int(e)
P = [complex(*map(float, input().split(','))) for _ in [0] * n]
Q = []
for i in range(n):
for j in range(i + 1, n):
Q += x(P[i], P[j])
print(max([sum(1.01 >= abs(q - p) for p in P) for q in Q] + [1]))
```
| 7,421 |
Provide a correct Python 3 solution for this coding contest problem.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
"Correct Solution:
```
import itertools
x=[0.]*100;y=[0.]*100
for e in iter(input,'0'):
a=0
n=int(e)
for i in range(n):x[i],y[i]=map(float,input().split(','))
for i,j in itertools.product(range(100),range(100)):
c=0
for k in range(n):
if pow(x[k]-(i/10),2)+pow(y[k]-(j/10),2)<=1.01:c+=1
if c>a:a=c
print(a)
```
| 7,422 |
Provide a correct Python 3 solution for this coding contest problem.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
"Correct Solution:
```
# AOJ 0090: Overlaps of Seals
# Python3 2018.6.28 bal4u
EPS = 1.0e-8
def crossPoint(p1, p2):
A = (p1.real-p2.real)/2
B = (p1.imag-p2.imag)/2
d = (A*A + B*B)**0.5
if d*d > 1.0 + EPS: return;
h = (1 - d*d)**0.5;
k, X, Y = h/d, (p1.real+p2.real)/2, (p1.imag+p2.imag)/2;
cross.append(complex(X+k*B, Y-k*A))
cross.append(complex(X-k*B, Y+k*A))
while True:
n = int(input())
if n == 0: break
circle = [0] * n
for i in range(n):
x, y = map(float, input().split(','))
circle[i] = complex(x, y)
cross = []
for i in range(n):
for j in range(i+1, n): crossPoint(circle[i], circle[j]);
ans = 0
for i in cross:
f = 0
for j in circle:
dx = j.real - i.real
dy = j.imag - i.imag
d = dx*dx + dy*dy
if abs(d-1.0) <= EPS or d <= 1.0: f += 1
if f > ans: ans = f
print(1 if ans == 0 else ans)
```
| 7,423 |
Provide a correct Python 3 solution for this coding contest problem.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
"Correct Solution:
```
# -*- coding: utf-8 -*-
import sys
import os
import math
for s in sys.stdin:
n = int(s)
if n == 0:
break
P = []
for i in range(n):
x, y = map(float, input().split(','))
P.append(complex(x, y))
def get_intersections(p0, p1):
"""
:type p0: complex
:type p1: complex
:return:
"""
dist = abs(p0 - p1)
if dist > 2:
return []
elif dist == 2:
return [(p0 + p1) / 2]
else:
m = (p0 + p1) / 2
v = m - p0
w = complex(v.imag, -v.real)
n = w / abs(w)
d = abs(v)
l = math.sqrt(1 - d ** 2)
inter0 = m + l * n
inter1 = m - l * n
return [inter0, inter1]
intersections = []
for i in range(n):
for j in range(i+1, n):
intersections += get_intersections(P[i], P[j])
counts = []
# each intersection, it is in how many circles?
for intersection in intersections:
cnt = 0
for p in P:
if abs(intersection - p) <= 1.01:
cnt += 1
counts.append(cnt)
if counts:
print(max(counts))
else:
print(1)
```
| 7,424 |
Provide a correct Python 3 solution for this coding contest problem.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
"Correct Solution:
```
def get_intersections(p0, p1):
dist = abs(p0 - p1)
if dist > 2:
return []
elif dist == 2:
return [(p0 + p1) / 2]
else:
m = (p0 + p1) / 2
v = m - p0
w = complex(v.imag, -v.real)
n = w / abs(w)
d = abs(v)
l = (1 - d ** 2)**.5
inter0 = m + l * n
inter1 = m - l * n
return [inter0, inter1]
for e in iter(input, '0'):
n = int(e)
P = [complex(*map(float,input().split(',')))for _ in[0]*n]
intersections = []
for i in range(n):
for j in range(i+1,n):
intersections += get_intersections(P[i], P[j])
c = 1
for intersection in intersections:
cnt = 0
for p in P:
if abs(intersection - p) <= 1.01:
cnt += 1
c=max(c,cnt)
print(c)
```
| 7,425 |
Provide a correct Python 3 solution for this coding contest problem.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
"Correct Solution:
```
import sys
import os
import math
for s in sys.stdin:
n = int(s)
if n == 0:
break
P = []
for i in range(n):
x, y = map(float, input().split(','))
P.append(complex(x, y))
def get_intersections(p0, p1):
"""
:type p0: complex
:type p1: complex
:return:
"""
dist = abs(p0 - p1)
if dist > 2:
return []
elif dist == 2:
return [(p0 + p1) / 2]
else:
m = (p0 + p1) / 2
v = m - p0
w = complex(v.imag, -v.real)
n = w / abs(w)
d = abs(v)
l = math.sqrt(1 - d ** 2)
inter0 = m + l * n
inter1 = m - l * n
return [inter0, inter1]
intersections = []
for i in range(n):
for j in range(i+1, n):
intersections += get_intersections(P[i], P[j])
counts = []
# each intersection, it is in how many circles?
for intersection in intersections:
cnt = 0
for p in P:
if abs(intersection - p) <= 1.01:
cnt += 1
counts.append(cnt)
if counts:
print(max(counts))
else:
print(1)
```
| 7,426 |
Provide a correct Python 3 solution for this coding contest problem.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
"Correct Solution:
```
def x(p0, p1):
d = abs(p0 - p1)
if d > 2:
return []
elif d == 2:
return [(p0 + p1) / 2]
else:
m = (p0 + p1) / 2
v = m - p0
w = complex(v.imag, -v.real)
l = abs(w)
h = (1 - l ** 2) ** .5 * w / l
return [m + h, m - h]
for e in iter(input, '0'):
n = int(e)
P = [complex(*map(float, input().split(','))) for _ in [0] * n]
Q = []
for i in range(n):
for j in range(i + 1, n):
Q += x(P[i], P[j])
print(max([sum(1.02 >= abs(q - p) for p in P) for q in Q] + [1]))
```
| 7,427 |
Provide a correct Python 3 solution for this coding contest problem.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
"Correct Solution:
```
def x(p0, p1):
d = abs(p0 - p1)
if d > 2:
return []
elif d == 2:
return [(p0 + p1) / 2]
else:
m = (p0 + p1) / 2
v = m - p0
w = complex(v.imag, -v.real)
l = abs(w)
h = (1 - l ** 2) ** .5 * w / l
return [m + h, m - h]
for e in iter(input, '0'):
n = int(e)
P = [complex(*map(float, input().split(','))) for _ in [0] * n]
Q = []
for i in range(n):
for j in range(i + 1, n):
Q += x(P[i], P[j])
print(max(sum(1.01 >= abs(q - p) for p in P) for q in Q) if Q else 1)
```
| 7,428 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
Submitted Solution:
```
import math
def dist(p1, p2):
return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)
def intersection(o1,o2):
if dist(o1,o2) > 2:
p1, p2 = [None, None], [None, None]
elif dist(o1,o2) == 2:
p1, p2 = [(o1[0] + o2[0])/2, (o1[1] + o2[1])/2], [None, None]
else:
m = [(o1[0] + o2[0])/2, (o1[1] + o2[1])/2]
v = [m[0] - o1[0], m[1] - o1[1]]
v_abs = dist(v,[0,0])
w = [v[1], -v[0]]
w_abs = dist(w,[0,0])
n = [w[0]/w_abs, w[1]/w_abs]
l = math.sqrt(1 - v_abs**2)
p1 = [m[0] + l*n[0], m[1] + l*n[1]]
p2 = [m[0] - l*n[0], m[1] - l*n[1]]
return p1, p2
err = 1.0e-6
while True:
n = int(input())
if n == 0:
break
p = []
for i in range(n):
p.append(list(map(float, input().split(","))))
ans = 1
for i in range(n - 1):
for j in range(i + 1, n):
p1, p2 = intersection(p[i], p[j])
cnt1 = 0
cnt2 = 0
for k in range(n):
if p1[0] and dist(p1, p[k]) <= 1 + err:
cnt1 += 1
if p2[0] and dist(p2, p[k]) <= 1 + err:
cnt2 += 1
ans = max([ans, cnt1, cnt2])
print(ans)
```
Yes
| 7,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
Submitted Solution:
```
import math
while 1:
N = int(input())
if N == 0:
break
PS = []
for i in range(N):
x, y = map(float, input().split(','))
PS.append((int(x * 100000), int(y * 100000)))
D2 = 100000**2
ans = 0
for i in range(101):
py = i * 10000
for j in range(101):
px = j * 10000
cnt = 0
for x, y in PS:
if (px - x) ** 2 + (py - y) ** 2 <= D2:
cnt += 1
ans = max(ans, cnt)
print(ans)
```
Yes
| 7,430 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
Submitted Solution:
```
import itertools
x=[0.]*100;y=[0.]*100
while 1:
n=int(input())
if n==0:break
a=0
for i in range(n):x[i],y[i]=map(float,input().split(','))
for i,j in itertools.product(range(100),range(100)):
c=0
for k in range(n):
if pow(x[k]-(i/10),2)+pow(y[k]-(j/10),2)<=1.01:c+=1
if c>a:a=c
print(a)
```
Yes
| 7,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
Submitted Solution:
```
import math
def overlap(p1, p2, d):
return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 <= d
def intersection(o1,o2):
a = 2*(o2[0] - o1[0])
b = 2*(o2[1] - o1[1])
c = (o1[0] - o2[0])*(o1[0] + o2[0]) + (o1[1] - o2[1])*(o1[1] + o2[1])
a2 = a**2 + b**2
b2 = a*c + a*b*o1[1] - b**2*o1[0]
c2 = b**2*(o1[0]**2 + o1[1]**2 - 1) + c**2 + 2*b*c*o1[1]
x1 = (-b2 + math.sqrt(abs(b2**2 - a2*c2)))/a2
x2 = (-b2 - math.sqrt(abs(b2**2 - a2*c2)))/a2
if abs(b) < 10e-8:
y1 = (o1[1] + o2[1])/2
y2 = (o1[1] + o2[1])/2
else:
y1 = -(a*x1 + c)/b
y2 = -(a*x2 + c)/b
if abs(b2**2 - a2*c2) < 10e-8:
return [x1, y1], [None, None]
else:
return [x1, y1], [x2, y2]
while True:
n = int(input())
if n == 0:
break
p = []
for i in range(n):
p.append(list(map(float, input().split(","))))
ans = 0
for i in range(n - 1):
for j in range(i + 1, n):
if not overlap(p[i], p[j], 4):
continue
elif overlap(p[i], p[j], 10e-8):
continue
p1, p2 = intersection(p[i], p[j])
cnt1 = 0
cnt2 = 0
for k in range(n):
if overlap(p1, p[k], 1):
cnt1 += 1
if p2[0] != None and overlap(p2, p[k], 1):
cnt2 += 1
ans = max([ans, cnt1, cnt2])
print(ans)
```
No
| 7,432 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
Submitted Solution:
```
import math
def overlap(p1, p2, d):
return abs((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 - d**2) <= 1.0e-6
def intersection(o1,o2):
a = 2*(o2[0] - o1[0])
b = 2*(o2[1] - o1[1])
c = (o1[0] - o2[0])*(o1[0] + o2[0]) + (o1[1] - o2[1])*(o1[1] + o2[1])
a2 = a**2 + b**2
b2 = a*c + a*b*o1[1] - b**2*o1[0]
c2 = b**2*(o1[0]**2 + o1[1]**2 - 1) + c**2 + 2*b*c*o1[1]
x1 = (-b2 + math.sqrt(b2**2 - a2*c2))/a2
x2 = (-b2 - math.sqrt(b2**2 - a2*c2))/a2
if abs(b) == 0:
y1 = o1[1] + math.sqrt(1 - (x1 - o1[0])**2)
y2 = o1[1] - math.sqrt(1 - (x1 - o1[0])**2)
else:
y1 = -(a*x1 + c)/b
y2 = -(a*x2 + c)/b
return [x1, y1], [x2, y2]
while True:
n = int(input())
if n == 0:
break
p = []
for i in range(n):
p.append(list(map(float, input().split(","))))
ans = 1
for i in range(n - 1):
for j in range(i + 1, n):
if not overlap(p[i], p[j], 2):
continue
p1, p2 = intersection(p[i], p[j])
cnt1 = 0
cnt2 = 0
for k in range(n):
if overlap(p1, p[k], 1):
cnt1 += 1
if overlap(p2, p[k], 1):
cnt2 += 1
ans = max([ans, cnt1, cnt2])
print(ans)
```
No
| 7,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
Submitted Solution:
```
import math
def overlap(p1, p2, d):
return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 <= d**2
def intersection(o1,o2):
a = 2*(o2[0] - o1[0])
b = 2*(o2[1] - o1[1])
c = (o1[0] - o2[0])*(o1[0] + o2[0]) + (o1[1] - o2[1])*(o1[1] + o2[1])
a2 = a**2 + b**2
b2 = a*c + a*b*o1[1] - b**2*o1[0]
c2 = b**2*(o1[0]**2 + o1[1]**2 - 1) + c**2 + 2*b*c*o1[1]
judge = b2**2 - a2*c2
if judge < 0:
return None, None
elif abs(judge) < 1.0e-6:
x = -b2/a2
if abs(b) < 1.0e-6:
y = o1[1] + math.sqrt(1 - (x - o1[0])**2)
else:
y = -(a*x + c)/b
return [x,y], None
else:
x1 = (-b2 + math.sqrt(judge))/a2
x2 = (-b2 - math.sqrt(judge))/a2
if abs(b) < 1.0e-6:
y1 = o1[1] + math.sqrt(1 - (x1 - o1[0])**2)
y2 = o1[1] - math.sqrt(1 - (x1 - o1[0])**2)
else:
y1 = -(a*x1 + c)/b
y2 = -(a*x2 + c)/b
return [x1, y1], [x2, y2]
while True:
n = int(input())
if n == 0:
break
p = []
for i in range(n):
p.append(list(map(float, input().split(","))))
ans = 1
for i in range(n - 1):
for j in range(i + 1, n):
if not overlap(p[i], p[j], 2):
continue
p1, p2 = intersection(p[i], p[j])
cnt1 = 0
cnt2 = 0
for k in range(n):
if p1 and overlap(p1, p[k], 1):
cnt1 += 1
if p2 and overlap(p2, p[k], 1):
cnt2 += 1
ans = max([ans, cnt1, cnt2])
print(ans)
```
No
| 7,434 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Stick n circular stickers with a radius of 1 on a square origami paper with a side length of 10. The stickers can be stacked. Create a program that reads the coordinates of the position where the stickers are to be attached and outputs the number of stickers at the place where the stickers overlap most on the origami paper (assuming that even one sticker "overlaps"). ..
Gives the x and y coordinates with the lower left corner of the origami as the origin. Let's put the sticker with these x and y as the center of the circle. The center of the circle never goes out of the origami. Also, multiple stickers will not be attached at the same coordinates.
Hint
It is a figure with a sticker attached as shown in the input example. The circle represents the sticker, and the number represents the number of lines in the input example. At point (2.3, 4.6), the four stickers on the second, third, sixth, and tenth lines of the input example overlap.
<image>
The distance between the centers of 6 and 9 is 2.01293, so the seals do not overlap. The distance between the centers of 1 and 12 is 1.98231, so the seals overlap.
When two circles are in contact (when the distance between the centers is 2), they are assumed to overlap.
Input
Given multiple datasets. Each dataset is given in the following format:
n
x1, y1
x2, y2
::
xn, yn
The first line gives the number of stickers n (0 ≤ 100). The next n lines give the center coordinates of each seal. xi and yi represent the x and y coordinates of the center of the i-th sticker. Each value is given as a real number, including up to 6 digits after the decimal point.
When n is 0, it is the end of the input. The number of datasets does not exceed 50.
Output
For each data set, output the number of stickers (integer) at the place where the stickers overlap most on the origami paper.
Example
Input
15
3.14979,8.51743
2.39506,3.84915
2.68432,5.39095
5.61904,9.16332
7.85653,4.75593
2.84021,5.41511
1.79500,8.59211
7.55389,8.17604
4.70665,4.66125
1.63470,4.42538
7.34959,4.61981
5.09003,8.11122
5.24373,1.30066
0.13517,1.83659
7.57313,1.58150
0
Output
4
Submitted Solution:
```
# -*- coding: utf-8 -*-
import sys
import os
import math
for s in sys.stdin:
n = int(s)
if n == 0:
break
P = []
for i in range(n):
x, y = map(float, input().split(','))
P.append(complex(x, y))
def get_intersections(p0, p1):
"""
:type p0: complex
:type p1: complex
:return:
"""
dist = abs(p0 - p1)
if dist > 2:
return []
elif dist == 2:
return [(p0 + p1) / 2]
else:
m = (p0 + p1) / 2
v = m - p0
w = complex(v.imag, -v.real)
n = w / abs(w)
d = abs(v)
l = math.sqrt(1 - d ** 2)
inter0 = m + l * n
inter1 = m - l * n
return [inter0, inter1]
intersections = []
for i in range(n):
for j in range(i+1, n):
intersections += get_intersections(P[i], P[j])
counts = []
# each intersection, it is in how many circles?
for intersection in intersections:
cnt = 0
for p in P:
if abs(intersection - p) <= 1:
cnt += 1
counts.append(cnt)
if counts:
print(max(counts))
else:
print(1)
```
No
| 7,435 |
Provide a correct Python 3 solution for this coding contest problem.
A set of four prime numbers arranged like (a, a + 2, a + 6, a + 8) is called a quadruplet prime number. Of the four prime numbers that make up a quadruplet prime, the largest number is called the size of the quadruplet prime. For example, the smallest prime quadruplet is a set of (5, 7, 11, 13), which is 13 in size. The next largest prime quadruplet is the set of (11, 13, 17, 19), which is 19 in size.
Create a program that takes the integer n (13 ≤ n ≤ 10,000,000) as input and outputs the maximum size of the quadruplet prime numbers whose size is n or less.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. One integer n is given on one row for each dataset.
The number of datasets does not exceed 2000.
Output
Outputs the maximum prime quadruplet size on one line for each input dataset.
Example
Input
13
14
15
16
17
18
19
20
10000
0
Output
13
13
13
13
13
13
19
19
9439
"Correct Solution:
```
# AOJ 0222 Prime Quadruplet
# Python3 2018.6.23 bal4u
# From Wekipedia (https://en.wikipedia.org/wiki/Prime_quadruplet)
# All prime quadruplets except {5, 7, 11, 13} are of the form
# {30n + 11, 30n + 13, 30n + 17, 30n + 19} for some integer n.
MAX = 899
diff = (0,3,3,21,22,13,7,39,7,73, \
126,119,88,3,11,66,29,17,53,42, \
101,214,104,298,252,133,255,141,76,91, \
168,81,45,56,203,301,43,66,291,223, \
92,97,442,290,437,281,38,144,549,241, \
29,192,11,518,266,490,122,130,13,329, \
85,209,71,241,290,18,301,52,120,34, \
50,805,276,217,182,53,209,155,77,468, \
448,29,90,85,91,7,146,21,309,234, \
60,213,511,59,273,364,57,77,87,231, \
452,168,154,346,273,588,11,91,322,335, \
140,221,87,442,297,95,321,498,146,182, \
8,38,11,679,111,120,83,36,59,462, \
32,349,448,333,644,63,101,960,161,759, \
255,354,270,52,200,133,112,297,298,27, \
74,577,25,182,280,584,756,266,287,277, \
119,31,561,59,179,630,34,98,1,84, \
217,234,4,48,127,528,679,35,108,15, \
752,60,31,228,559,7,35,56,43,10, \
151,374,297,294,14,60,196,133,18,63, \
63,17,35,290,953,584,66,102,427,4, \
357,507,441,420,802,14,66,171,252,88, \
14,364,32,220,66,256,427,651,52,287, \
987,214,161,319,241,1333,190,325,63,500, \
1026,60,13,112,238,144,137,349,417,32, \
164,196,115,735,200,382,273,104,119,214, \
665,235,297,665,25,34,211,280,542,375, \
188,42,134,573,350,106,17,112,676,1095, \
403,62,193,60,13,116,60,255,609,350, \
7,165,661,25,748,176,10,283,144,987, \
389,59,60,342,112,144,31,98,676,297, \
652,189,56,34,441,50,314,266,29,546, \
297,39,657,46,703,70,270,221,122,767, \
13,134,318,1222,84,650,371,92,164,760, \
318,175,158,679,496,389,273,38,676,270, \
902,228,143,196,18,287,102,409,612,1, \
56,269,311,714,1092,176,34,165,143,438, \
266,249,97,442,105,7,913,81,80,871, \
497,585,574,11,220,94,855,132,473,836, \
301,7,833,63,1145,60,1886,382,111,43, \
111,319,431,108,297,60,878,799,133,472, \
529,420,241,46,231,304,616,1145,595,447, \
589,76,399,865,154,101,119,739,528,673, \
49,994,412,1072,6,25,3,49,126,1079, \
1141,66,220,932,1049,561,692,764,476,248, \
200,1897,658,644,24,399,143,1331,839,1, \
1077,760,11,34,658,36,647,21,528,242, \
98,529,24,1117,192,396,930,224,365,66, \
557,377,757,322,203,335,770,155,97,21, \
665,484,553,321,207,116,574,272,287,253, \
637,259,38,263,62,1268,451,693,756,630, \
357,105,32,581,455,153,540,350,91,210, \
409,270,377,442,490,615,424,52,890,199, \
102,1746,462,749,24,644,540,220,840,1656, \
223,74,434,179,665,923,428,307,875,50, \
2387,276,109,363,529,550,139,798,176,150, \
297,123,66,266,414,17,130,1344,300,1799, \
8,1176,279,351,461,396,112,626,498,931, \
2782,123,1253,780,781,1119,46,39,847,468, \
1037,1144,63,332,294,1082,525,459,220,70, \
231,31,1029,256,290,662,242,98,252,13, \
1008,64,346,1211,119,802,189,272,298,122, \
697,319,195,273,410,1221,365,885,322,52, \
847,165,112,67,812,630,801,87,60,424, \
630,867,231,123,308,396,76,119,60,203, \
17,63,553,931,147,588,127,437,164,43, \
14,371,115,150,354,315,473,3,1221,245, \
36,272,214,24,385,249,182,445,171,35, \
921,300,1558,1250,129,539,476,94,11,227, \
427,151,102,126,2176,71,297,60,413,195, \
190,944,49,554,1102,676,279,78,143,364, \
357,462,1144,1050,218,423,623,364,416,239, \
143,280,248,365,77,77,1529,157,361,514, \
536,31,330,87,193,514,935,227,18,91, \
104,49,133,1149,104,518,396,1015,143,445, \
360,385,680,49,1053,669,647,931,140,231, \
31,1075,483,627,101,1012,714,346,504,60, \
917,1140,1180,98,297,1029,225,1918,406,188, \
368,466,1305,1117,1028,50,150,273,333,101, \
151,146,1100,119,1532,497,487,235,658,322, \
538,210,701,574,136,220,168,105,603,332, \
409,84,81,39,860,309,384,259,266,207, \
872,377,403,248,819,882,931,148,42,371, \
805,325,668,529,409,3151,2016,14,38,1487, \
350,295,266,343,1833,1887,123,370,260,696, \
137,962,410,132,847,1051,426,39,214,546, \
539,493,325,137,112,889,130,237,43,1183, \
118,371,1,580,316,434,2698,53,98,262, \
203,119,31,189,813,119,195,294,1435,1345, \
531,624,210,231,321,553,11,756,1358)
import bisect
tbl = [0]*MAX
for i in range(1, MAX): tbl[i] = tbl[i-1] + diff[i]
for i in range(MAX): tbl[i] = tbl[i]*30+19
while 1:
n = int(input())
if n == 0: break
if n < 19: print("13")
else:
p = bisect.bisect_left(tbl, n)
if tbl[p] == n: print(n)
else: print(tbl[p-1])
```
| 7,436 |
Provide a correct Python 3 solution for this coding contest problem.
A set of four prime numbers arranged like (a, a + 2, a + 6, a + 8) is called a quadruplet prime number. Of the four prime numbers that make up a quadruplet prime, the largest number is called the size of the quadruplet prime. For example, the smallest prime quadruplet is a set of (5, 7, 11, 13), which is 13 in size. The next largest prime quadruplet is the set of (11, 13, 17, 19), which is 19 in size.
Create a program that takes the integer n (13 ≤ n ≤ 10,000,000) as input and outputs the maximum size of the quadruplet prime numbers whose size is n or less.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. One integer n is given on one row for each dataset.
The number of datasets does not exceed 2000.
Output
Outputs the maximum prime quadruplet size on one line for each input dataset.
Example
Input
13
14
15
16
17
18
19
20
10000
0
Output
13
13
13
13
13
13
19
19
9439
"Correct Solution:
```
# AOJ 0222 Prime Quadruplet
# Python3 2018.6.23 bal4u
# From Wekipedia (https://en.wikipedia.org/wiki/Prime_quadruplet)
# All prime quadruplets except {5, 7, 11, 13} are of the form
# {30n + 11, 30n + 13, 30n + 17, 30n + 19} for some integer n.
MAX = 899
diff = (0,3,3,21,22,13,7,39,7,73, \
126,119,88,3,11,66,29,17,53,42, \
101,214,104,298,252,133,255,141,76,91, \
168,81,45,56,203,301,43,66,291,223, \
92,97,442,290,437,281,38,144,549,241, \
29,192,11,518,266,490,122,130,13,329, \
85,209,71,241,290,18,301,52,120,34, \
50,805,276,217,182,53,209,155,77,468, \
448,29,90,85,91,7,146,21,309,234, \
60,213,511,59,273,364,57,77,87,231, \
452,168,154,346,273,588,11,91,322,335, \
140,221,87,442,297,95,321,498,146,182, \
8,38,11,679,111,120,83,36,59,462, \
32,349,448,333,644,63,101,960,161,759, \
255,354,270,52,200,133,112,297,298,27, \
74,577,25,182,280,584,756,266,287,277, \
119,31,561,59,179,630,34,98,1,84, \
217,234,4,48,127,528,679,35,108,15, \
752,60,31,228,559,7,35,56,43,10, \
151,374,297,294,14,60,196,133,18,63, \
63,17,35,290,953,584,66,102,427,4, \
357,507,441,420,802,14,66,171,252,88, \
14,364,32,220,66,256,427,651,52,287, \
987,214,161,319,241,1333,190,325,63,500, \
1026,60,13,112,238,144,137,349,417,32, \
164,196,115,735,200,382,273,104,119,214, \
665,235,297,665,25,34,211,280,542,375, \
188,42,134,573,350,106,17,112,676,1095, \
403,62,193,60,13,116,60,255,609,350, \
7,165,661,25,748,176,10,283,144,987, \
389,59,60,342,112,144,31,98,676,297, \
652,189,56,34,441,50,314,266,29,546, \
297,39,657,46,703,70,270,221,122,767, \
13,134,318,1222,84,650,371,92,164,760, \
318,175,158,679,496,389,273,38,676,270, \
902,228,143,196,18,287,102,409,612,1, \
56,269,311,714,1092,176,34,165,143,438, \
266,249,97,442,105,7,913,81,80,871, \
497,585,574,11,220,94,855,132,473,836, \
301,7,833,63,1145,60,1886,382,111,43, \
111,319,431,108,297,60,878,799,133,472, \
529,420,241,46,231,304,616,1145,595,447, \
589,76,399,865,154,101,119,739,528,673, \
49,994,412,1072,6,25,3,49,126,1079, \
1141,66,220,932,1049,561,692,764,476,248, \
200,1897,658,644,24,399,143,1331,839,1, \
1077,760,11,34,658,36,647,21,528,242, \
98,529,24,1117,192,396,930,224,365,66, \
557,377,757,322,203,335,770,155,97,21, \
665,484,553,321,207,116,574,272,287,253, \
637,259,38,263,62,1268,451,693,756,630, \
357,105,32,581,455,153,540,350,91,210, \
409,270,377,442,490,615,424,52,890,199, \
102,1746,462,749,24,644,540,220,840,1656, \
223,74,434,179,665,923,428,307,875,50, \
2387,276,109,363,529,550,139,798,176,150, \
297,123,66,266,414,17,130,1344,300,1799, \
8,1176,279,351,461,396,112,626,498,931, \
2782,123,1253,780,781,1119,46,39,847,468, \
1037,1144,63,332,294,1082,525,459,220,70, \
231,31,1029,256,290,662,242,98,252,13, \
1008,64,346,1211,119,802,189,272,298,122, \
697,319,195,273,410,1221,365,885,322,52, \
847,165,112,67,812,630,801,87,60,424, \
630,867,231,123,308,396,76,119,60,203, \
17,63,553,931,147,588,127,437,164,43, \
14,371,115,150,354,315,473,3,1221,245, \
36,272,214,24,385,249,182,445,171,35, \
921,300,1558,1250,129,539,476,94,11,227, \
427,151,102,126,2176,71,297,60,413,195, \
190,944,49,554,1102,676,279,78,143,364, \
357,462,1144,1050,218,423,623,364,416,239, \
143,280,248,365,77,77,1529,157,361,514, \
536,31,330,87,193,514,935,227,18,91, \
104,49,133,1149,104,518,396,1015,143,445, \
360,385,680,49,1053,669,647,931,140,231, \
31,1075,483,627,101,1012,714,346,504,60, \
917,1140,1180,98,297,1029,225,1918,406,188, \
368,466,1305,1117,1028,50,150,273,333,101, \
151,146,1100,119,1532,497,487,235,658,322, \
538,210,701,574,136,220,168,105,603,332, \
409,84,81,39,860,309,384,259,266,207, \
872,377,403,248,819,882,931,148,42,371, \
805,325,668,529,409,3151,2016,14,38,1487, \
350,295,266,343,1833,1887,123,370,260,696, \
137,962,410,132,847,1051,426,39,214,546, \
539,493,325,137,112,889,130,237,43,1183, \
118,371,1,580,316,434,2698,53,98,262, \
203,119,31,189,813,119,195,294,1435,1345, \
531,624,210,231,321,553,11,756,1358)
def bsch(x):
l, r = 0, MAX
while l < r:
m = (l + r) >> 1
if tbl[m] == x: return m
if tbl[m] < x: l = m+1
else: r = m
return l-1;
tbl = [0]*MAX
for i in range(1, MAX): tbl[i] = tbl[i-1] + diff[i]
for i in range(MAX): tbl[i] = tbl[i]*30+19
while 1:
n = int(input())
if n == 0: break
if n < 19: print("13")
else: print(tbl[bsch(n)])
```
| 7,437 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A set of four prime numbers arranged like (a, a + 2, a + 6, a + 8) is called a quadruplet prime number. Of the four prime numbers that make up a quadruplet prime, the largest number is called the size of the quadruplet prime. For example, the smallest prime quadruplet is a set of (5, 7, 11, 13), which is 13 in size. The next largest prime quadruplet is the set of (11, 13, 17, 19), which is 19 in size.
Create a program that takes the integer n (13 ≤ n ≤ 10,000,000) as input and outputs the maximum size of the quadruplet prime numbers whose size is n or less.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. One integer n is given on one row for each dataset.
The number of datasets does not exceed 2000.
Output
Outputs the maximum prime quadruplet size on one line for each input dataset.
Example
Input
13
14
15
16
17
18
19
20
10000
0
Output
13
13
13
13
13
13
19
19
9439
Submitted Solution:
```
primes = [0, 0] + [1]*999999
for i in range(2, 1001):
for j in range(i*i, 1000001, i):
primes[j] = 0
while True:
n = int(input())
if n == 0:
break
for i in range(5, n+1)[::-1]:
if primes[i] and primes[i-2] and primes[i-6] and primes[i-8]:
print(i)
break
```
No
| 7,438 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A set of four prime numbers arranged like (a, a + 2, a + 6, a + 8) is called a quadruplet prime number. Of the four prime numbers that make up a quadruplet prime, the largest number is called the size of the quadruplet prime. For example, the smallest prime quadruplet is a set of (5, 7, 11, 13), which is 13 in size. The next largest prime quadruplet is the set of (11, 13, 17, 19), which is 19 in size.
Create a program that takes the integer n (13 ≤ n ≤ 10,000,000) as input and outputs the maximum size of the quadruplet prime numbers whose size is n or less.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. One integer n is given on one row for each dataset.
The number of datasets does not exceed 2000.
Output
Outputs the maximum prime quadruplet size on one line for each input dataset.
Example
Input
13
14
15
16
17
18
19
20
10000
0
Output
13
13
13
13
13
13
19
19
9439
Submitted Solution:
```
def get_quad(n, p):
for ni in range(n,0,-1):
if p[ni] and p[ni - 2] and p[ni - 6] and p[ni - 8]:
return ni
def sieve():
n = 10000001
p = [1] * n
p[0] = p[1] = 0
for i in range(int(n ** 0.5)):
if p[i]:
for j in range(2 * i, len(p), i):
p[j] = 0
return p
import sys
f = sys.stdin
prime = sieve()
while True:
n = f.readline()
if not n.isnumeric():
continue
n = int(n)
if n == 0:
break
print(get_quad(ni, prime))
```
No
| 7,439 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A set of four prime numbers arranged like (a, a + 2, a + 6, a + 8) is called a quadruplet prime number. Of the four prime numbers that make up a quadruplet prime, the largest number is called the size of the quadruplet prime. For example, the smallest prime quadruplet is a set of (5, 7, 11, 13), which is 13 in size. The next largest prime quadruplet is the set of (11, 13, 17, 19), which is 19 in size.
Create a program that takes the integer n (13 ≤ n ≤ 10,000,000) as input and outputs the maximum size of the quadruplet prime numbers whose size is n or less.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. One integer n is given on one row for each dataset.
The number of datasets does not exceed 2000.
Output
Outputs the maximum prime quadruplet size on one line for each input dataset.
Example
Input
13
14
15
16
17
18
19
20
10000
0
Output
13
13
13
13
13
13
19
19
9439
Submitted Solution:
```
def get_quad(n, p):
return 0
def sieve():
n = 10000001
p = [1] * n
p[0] = p[1] = 0
for i in range(int(n ** 0.5)):
if p[i]:
for j in range(2 * i, len(p), i):
p[j] = 0
return p
import sys
f = sys.stdin
prime = sieve()
while True:
ni = int(f.readline())
if ni == 0:
break
print(get_quad(ni, prime))
```
No
| 7,440 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A set of four prime numbers arranged like (a, a + 2, a + 6, a + 8) is called a quadruplet prime number. Of the four prime numbers that make up a quadruplet prime, the largest number is called the size of the quadruplet prime. For example, the smallest prime quadruplet is a set of (5, 7, 11, 13), which is 13 in size. The next largest prime quadruplet is the set of (11, 13, 17, 19), which is 19 in size.
Create a program that takes the integer n (13 ≤ n ≤ 10,000,000) as input and outputs the maximum size of the quadruplet prime numbers whose size is n or less.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. One integer n is given on one row for each dataset.
The number of datasets does not exceed 2000.
Output
Outputs the maximum prime quadruplet size on one line for each input dataset.
Example
Input
13
14
15
16
17
18
19
20
10000
0
Output
13
13
13
13
13
13
19
19
9439
Submitted Solution:
```
primes = [0, 0] + [1] * 9999999
for i in range(2, 3163):
if primes[i]:
for j in range(i*i, 10000001, i):
primes[j] = 0
while True:
n = int(input())
if n == 0:
break
for i in range(5, n+1)[::-1]:
if primes[i-8] & primes[i-6] & primes[i-2] & primes[i]):
print(i)
break
```
No
| 7,441 |
Provide a correct Python 3 solution for this coding contest problem.
The Aizu Wakamatsu city office decided to lay a hot water pipeline covering the whole area of the city to heat houses. The pipeline starts from some hot springs and connects every district in the city. The pipeline can fork at a hot spring or a district, but no cycle is allowed. The city office wants to minimize the length of pipeline in order to build it at the least possible expense.
Write a program to compute the minimal length of the pipeline. The program reads an input that consists of the following three parts:
Hint
The first line correspondings to the first part: there are three hot springs and five districts. The following three lines are the second part: the distances between a hot spring and a district. For instance, the distance between the first hot spring and the third district is 25. The last four lines are the third part: the distances between two districts. For instance, the distance between the second and the third districts is 9. The second hot spring and the fourth district are not connectable The second and the fifth districts are not connectable, either.
Input
* The first part consists of two positive integers in one line, which represent the number s of hot springs and the number d of districts in the city, respectively.
* The second part consists of s lines: each line contains d non-negative integers. The i-th integer in the j-th line represents the distance between the j-th hot spring and the i-th district if it is non-zero. If zero it means they are not connectable due to an obstacle between them.
* The third part consists of d-1 lines. The i-th line has d - i non-negative integers. The i-th integer in the j-th line represents the distance between the j-th and the (i + j)-th districts if it is non-zero. The meaning of zero is the same as mentioned above.
For the sake of simplicity, you can assume the following:
* The number of hot springs and that of districts do not exceed 50.
* Each distance is no more than 100.
* Each line in the input file contains at most 256 characters.
* Each number is delimited by either whitespace or tab.
The input has several test cases. The input terminate with a line which has two 0. The number of test cases is less than 20.
Output
Output the minimum length of pipeline for each test case.
Example
Input
3 5
12 8 25 19 23
9 13 16 0 17
20 14 16 10 22
17 27 18 16
9 7 0
19 5
21
0 0
Output
38
"Correct Solution:
```
while(1):
s,d=[int(x) for x in input().split()]
A=[999 for x in range(d)]
if s==0: break
for j in range(s):
l=[int(x) for x in input().split()]
for i in range(d):
if l[i]!=0:
A[i]=min(A[i], l[i])
B=[[999 for x in range(d)] for y in range(d)]
for j in range(d-1):
l=[int(x) for x in input().split()]
for i in range(d-1-j):
if l[i]!=0:
B[j][i+j+1]=l[i]
B[i+j+1][j]=l[i]
notevaled=[1 for x in range(d)]
ans=0
for i in range(d):
mini=A.index(min(A))
ans+=A[mini]
notevaled[mini]=0
A[mini]=999
for x in range(d):
if notevaled[x]:
A[x]=min( A[x], B[mini][x] )
print(ans)
```
| 7,442 |
Provide a correct Python 3 solution for this coding contest problem.
The Aizu Wakamatsu city office decided to lay a hot water pipeline covering the whole area of the city to heat houses. The pipeline starts from some hot springs and connects every district in the city. The pipeline can fork at a hot spring or a district, but no cycle is allowed. The city office wants to minimize the length of pipeline in order to build it at the least possible expense.
Write a program to compute the minimal length of the pipeline. The program reads an input that consists of the following three parts:
Hint
The first line correspondings to the first part: there are three hot springs and five districts. The following three lines are the second part: the distances between a hot spring and a district. For instance, the distance between the first hot spring and the third district is 25. The last four lines are the third part: the distances between two districts. For instance, the distance between the second and the third districts is 9. The second hot spring and the fourth district are not connectable The second and the fifth districts are not connectable, either.
Input
* The first part consists of two positive integers in one line, which represent the number s of hot springs and the number d of districts in the city, respectively.
* The second part consists of s lines: each line contains d non-negative integers. The i-th integer in the j-th line represents the distance between the j-th hot spring and the i-th district if it is non-zero. If zero it means they are not connectable due to an obstacle between them.
* The third part consists of d-1 lines. The i-th line has d - i non-negative integers. The i-th integer in the j-th line represents the distance between the j-th and the (i + j)-th districts if it is non-zero. The meaning of zero is the same as mentioned above.
For the sake of simplicity, you can assume the following:
* The number of hot springs and that of districts do not exceed 50.
* Each distance is no more than 100.
* Each line in the input file contains at most 256 characters.
* Each number is delimited by either whitespace or tab.
The input has several test cases. The input terminate with a line which has two 0. The number of test cases is less than 20.
Output
Output the minimum length of pipeline for each test case.
Example
Input
3 5
12 8 25 19 23
9 13 16 0 17
20 14 16 10 22
17 27 18 16
9 7 0
19 5
21
0 0
Output
38
"Correct Solution:
```
# AOJ 1014: Computation of Minimum Length of Pipeline
# Python3 2018.7.5 bal4u
import sys
from sys import stdin
input = stdin.readline
import heapq
while True:
s, d = map(int, input().split())
if s == 0: break
visited = [0]*100
Q = []
to = [[] for i in range(100)]
for i in range(s):
visited[i] = 1
c = list(map(int, input().split()))
for j in range(d):
if c[j] > 0: heapq.heappush(Q, (c[j], i, s+j))
for i in range(d-1):
c = list(map(int, input().split()))
for j in range(i+1, d):
if c[j-i-1] > 0:
to[s+i].append((s+j, c[j-i-1]))
to[s+j].append((s+i, c[j-i-1]))
ans = k = 0
while k < d:
while True:
c, a, b = heapq.heappop(Q)
if visited[a] == 0 or visited[b] == 0: break
ans, k = ans+c, k+1
if visited[a]: a = b
visited[a] = 1;
for e, c in to[a]:
if visited[e] == 0: heapq.heappush(Q, (c, a, e))
print(ans)
```
| 7,443 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Aizu Wakamatsu city office decided to lay a hot water pipeline covering the whole area of the city to heat houses. The pipeline starts from some hot springs and connects every district in the city. The pipeline can fork at a hot spring or a district, but no cycle is allowed. The city office wants to minimize the length of pipeline in order to build it at the least possible expense.
Write a program to compute the minimal length of the pipeline. The program reads an input that consists of the following three parts:
Hint
The first line correspondings to the first part: there are three hot springs and five districts. The following three lines are the second part: the distances between a hot spring and a district. For instance, the distance between the first hot spring and the third district is 25. The last four lines are the third part: the distances between two districts. For instance, the distance between the second and the third districts is 9. The second hot spring and the fourth district are not connectable The second and the fifth districts are not connectable, either.
Input
* The first part consists of two positive integers in one line, which represent the number s of hot springs and the number d of districts in the city, respectively.
* The second part consists of s lines: each line contains d non-negative integers. The i-th integer in the j-th line represents the distance between the j-th hot spring and the i-th district if it is non-zero. If zero it means they are not connectable due to an obstacle between them.
* The third part consists of d-1 lines. The i-th line has d - i non-negative integers. The i-th integer in the j-th line represents the distance between the j-th and the (i + j)-th districts if it is non-zero. The meaning of zero is the same as mentioned above.
For the sake of simplicity, you can assume the following:
* The number of hot springs and that of districts do not exceed 50.
* Each distance is no more than 100.
* Each line in the input file contains at most 256 characters.
* Each number is delimited by either whitespace or tab.
The input has several test cases. The input terminate with a line which has two 0. The number of test cases is less than 20.
Output
Output the minimum length of pipeline for each test case.
Example
Input
3 5
12 8 25 19 23
9 13 16 0 17
20 14 16 10 22
17 27 18 16
9 7 0
19 5
21
0 0
Output
38
Submitted Solution:
```
while(1):
s,d=[int(x) for x in input().split()]
A=[999 for x in range(d)]
if s==0: break
for j in range(s):
l=[int(x) for x in input().split()]
for i in range(d):
if l[i]!=0:
A[i]=min(A[i], l[i])
B=[[999 for x in range(d)] for y in range(d)]
for j in range(d-1):
l=[int(x) for x in input().split()]
for i in range(d-1-j):
if l[i]!=0:
B[i][i+j+1]=l[i]
B[i+j+1][i]=l[i]
notevaled=[1 for x in range(d)]
ans=0
for i in range(d):
mini=A.index(min(A))
ans+=A[mini]
notevaled[mini]=0
A[mini]=999
for x in range(d):
if notevaled[x]:
A[x]=min( A[x], B[mini][x] )
print(ans)
```
No
| 7,444 |
Provide a correct Python 3 solution for this coding contest problem.
Three-valued logic is a logic system that has, in addition to "true" and "false", "unknown" as a valid value. In the following, logical values "false", "unknown" and "true" are represented by 0, 1 and 2 respectively.
Let "-" be a unary operator (i.e. a symbol representing one argument function) and let both "*" and "+" be binary operators (i.e. symbols representing two argument functions). These operators represent negation (NOT), conjunction (AND) and disjunction (OR) respectively. These operators in three-valued logic can be defined in Table C-1.
Table C-1: Truth tables of three-valued logic operators
-X| | (X*Y)| | (X+Y) | <image>| | <image>| | <image> |
---|---|---|---|---|---
Let P, Q and R be variables ranging over three-valued logic values. For a given formula, you are asked to answer the number of triples (P,Q,R) that satisfy the formula, that is, those which make the value of the given formula 2. A formula is one of the following form (X and Y represent formulas).
* Constants: 0, 1 or 2
* Variables: P, Q or R
* Negations: -X
* Conjunctions: (X*Y)
* Disjunctions: (X+Y)
Note that conjunctions and disjunctions of two formulas are always parenthesized.
For example, when formula (P*Q) is given as an input, the value of this formula is 2 when and only when (P,Q,R) is (2,2,0), (2,2,1) or (2,2,2). Therefore, you should output 3.
Input
The input consists of one or more lines. Each line contains a formula. A formula is a string which consists of 0, 1, 2, P, Q, R, -, *, +, (, ). Other characters such as spaces are not contained. The grammar of formulas is given by the following BNF.
<formula> ::= 0 | 1 | 2 | P | Q | R |
-<formula> | (<formula>*<formula>) | (<formula>+<formula>)
All the formulas obey this syntax and thus you do not have to care about grammatical errors. Input lines never exceed 80 characters.
Finally, a line which contains only a "." (period) comes, indicating the end of the input.
Output
You should answer the number (in decimal) of triples (P,Q,R) that make the value of the given formula 2. One line containing the number should be output for each of the formulas, and no other characters should be output.
Sample Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output for the Sample Input
3
11
0
27
0
7
Example
Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output
3
11
0
27
0
7
"Correct Solution:
```
def parser(left, right):
if S[left] == '(' and S[right - 1] == ')':
cnt = 0
for i in range(left + 1, right - 1):
if S[i] == '(':
cnt += 1
elif S[i] == ')':
cnt -= 1
elif cnt == 0 and S[i] == '+':
return [max(x, y) for x, y in zip(parser(left + 1, i), parser(i + 1, right - 1))]
elif cnt == 0 and S[i] == '*':
return [min(x, y) for x, y in zip(parser(left + 1, i), parser(i + 1, right - 1))]
elif S[left] == '-':
return [2 - x for x in parser(left + 1, right)]
elif S[left] == 'P':
return [i // 9 % 3 for i in range(27)]
elif S[left] == 'Q':
return [i // 3 % 3 for i in range(27)]
elif S[left] == 'R':
return [i % 3 for i in range(27)]
else:
return [int(S[left]) for _ in range(27)]
while True:
S = input()
if S == '.':
break
print(parser(0, len(S)).count(2))
```
| 7,445 |
Provide a correct Python 3 solution for this coding contest problem.
Three-valued logic is a logic system that has, in addition to "true" and "false", "unknown" as a valid value. In the following, logical values "false", "unknown" and "true" are represented by 0, 1 and 2 respectively.
Let "-" be a unary operator (i.e. a symbol representing one argument function) and let both "*" and "+" be binary operators (i.e. symbols representing two argument functions). These operators represent negation (NOT), conjunction (AND) and disjunction (OR) respectively. These operators in three-valued logic can be defined in Table C-1.
Table C-1: Truth tables of three-valued logic operators
-X| | (X*Y)| | (X+Y) | <image>| | <image>| | <image> |
---|---|---|---|---|---
Let P, Q and R be variables ranging over three-valued logic values. For a given formula, you are asked to answer the number of triples (P,Q,R) that satisfy the formula, that is, those which make the value of the given formula 2. A formula is one of the following form (X and Y represent formulas).
* Constants: 0, 1 or 2
* Variables: P, Q or R
* Negations: -X
* Conjunctions: (X*Y)
* Disjunctions: (X+Y)
Note that conjunctions and disjunctions of two formulas are always parenthesized.
For example, when formula (P*Q) is given as an input, the value of this formula is 2 when and only when (P,Q,R) is (2,2,0), (2,2,1) or (2,2,2). Therefore, you should output 3.
Input
The input consists of one or more lines. Each line contains a formula. A formula is a string which consists of 0, 1, 2, P, Q, R, -, *, +, (, ). Other characters such as spaces are not contained. The grammar of formulas is given by the following BNF.
<formula> ::= 0 | 1 | 2 | P | Q | R |
-<formula> | (<formula>*<formula>) | (<formula>+<formula>)
All the formulas obey this syntax and thus you do not have to care about grammatical errors. Input lines never exceed 80 characters.
Finally, a line which contains only a "." (period) comes, indicating the end of the input.
Output
You should answer the number (in decimal) of triples (P,Q,R) that make the value of the given formula 2. One line containing the number should be output for each of the formulas, and no other characters should be output.
Sample Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output for the Sample Input
3
11
0
27
0
7
Example
Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output
3
11
0
27
0
7
"Correct Solution:
```
def parseParenthesis(formula):
pos = 0
count = 0
while True:
if formula[pos] == '(':
count += 1
elif formula[pos] == ')':
count -= 1
elif count == 1 and (formula[pos] == '+' or formula[pos] == '*'):
sign = formula[pos]
formulaA = formula[1:pos]
formulaB = formula[pos + 1: -1]
return formulaA, sign, formulaB
pos += 1
def eval_or(a, b):
if a == '0':
return b
elif a == '1':
return '1' if b == '0' else b
elif a == '2':
return '2'
def eval_and(a, b):
if a == '0':
return '0'
elif a == '1':
return '0' if b == '0' else '1'
elif a == '2':
return b
def eval_neg(a):
if a == '1':
return '1'
return '2' if a == '0' else '0'
def evaluate(formula, p, q, r):
if formula == '0' or formula == '1' or formula == '2':
return formula
if formula == 'P':
return p
if formula == 'Q':
return q
if formula == 'R':
return r
if formula[0] == '(':
formulaA, sign, formulaB = parseParenthesis(formula)
evalA = evaluate(formulaA, p, q, r)
evalB = evaluate(formulaB, p, q, r)
if sign == '+':
return eval_or(evalA, evalB)
elif sign == '*':
return eval_and(evalA, evalB)
elif formula[0] == '-':
return eval_neg(evaluate(formula[1:], p, q, r))
if __name__ == '__main__':
while True:
formula = input().strip()
if formula == '.':
break
count = 0
for p in range(3):
for q in range(3):
for r in range(3):
if evaluate(formula, str(p), str(q), str(r)) == '2':
count += 1
print(count)
```
| 7,446 |
Provide a correct Python 3 solution for this coding contest problem.
Three-valued logic is a logic system that has, in addition to "true" and "false", "unknown" as a valid value. In the following, logical values "false", "unknown" and "true" are represented by 0, 1 and 2 respectively.
Let "-" be a unary operator (i.e. a symbol representing one argument function) and let both "*" and "+" be binary operators (i.e. symbols representing two argument functions). These operators represent negation (NOT), conjunction (AND) and disjunction (OR) respectively. These operators in three-valued logic can be defined in Table C-1.
Table C-1: Truth tables of three-valued logic operators
-X| | (X*Y)| | (X+Y) | <image>| | <image>| | <image> |
---|---|---|---|---|---
Let P, Q and R be variables ranging over three-valued logic values. For a given formula, you are asked to answer the number of triples (P,Q,R) that satisfy the formula, that is, those which make the value of the given formula 2. A formula is one of the following form (X and Y represent formulas).
* Constants: 0, 1 or 2
* Variables: P, Q or R
* Negations: -X
* Conjunctions: (X*Y)
* Disjunctions: (X+Y)
Note that conjunctions and disjunctions of two formulas are always parenthesized.
For example, when formula (P*Q) is given as an input, the value of this formula is 2 when and only when (P,Q,R) is (2,2,0), (2,2,1) or (2,2,2). Therefore, you should output 3.
Input
The input consists of one or more lines. Each line contains a formula. A formula is a string which consists of 0, 1, 2, P, Q, R, -, *, +, (, ). Other characters such as spaces are not contained. The grammar of formulas is given by the following BNF.
<formula> ::= 0 | 1 | 2 | P | Q | R |
-<formula> | (<formula>*<formula>) | (<formula>+<formula>)
All the formulas obey this syntax and thus you do not have to care about grammatical errors. Input lines never exceed 80 characters.
Finally, a line which contains only a "." (period) comes, indicating the end of the input.
Output
You should answer the number (in decimal) of triples (P,Q,R) that make the value of the given formula 2. One line containing the number should be output for each of the formulas, and no other characters should be output.
Sample Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output for the Sample Input
3
11
0
27
0
7
Example
Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output
3
11
0
27
0
7
"Correct Solution:
```
def parse_formula(s, pointer):
head = s[pointer]
if head == "-":
pointer += 1
result, pointer = parse_formula(s, pointer)
result = 2 - result
elif head == "(":
pointer += 1
result_left, pointer = parse_formula(s, pointer)
op, pointer = parse_op(s, pointer)
result_right, pointer = parse_formula(s, pointer)
result = calc(op, result_left, result_right)
pointer += 1
else:
result = int(head)
pointer += 1
return result, pointer
def parse_op(s, pointer):
return s[pointer], pointer + 1
calc_table1 = {(0, 0):0, (0, 1):0, (0, 2):0,
(1, 0):0, (1, 1):1, (1, 2):1,
(2, 0):0, (2, 1):1, (2, 2):2}
calc_table2 = {(0, 0):0, (0, 1):1, (0, 2):2,
(1, 0):1, (1, 1):1, (1, 2):2,
(2, 0):2, (2, 1):2, (2, 2):2}
def calc(op, left, right):
if op == "*":return calc_table1[(left, right)]
if op == "+":return calc_table2[(left, right)]
while True:
formula = input()
if formula == ".":
break
ans = 0
for p in ("0", "1", "2"):
sp = formula.replace("P", p)
for q in ("0", "1", "2"):
sq = sp.replace("Q", q)
for r in ("0", "1", "2"):
sr = sq.replace("R", r)
if parse_formula(sr, 0)[0] == 2:
ans += 1
print(ans)
```
| 7,447 |
Provide a correct Python 3 solution for this coding contest problem.
Three-valued logic is a logic system that has, in addition to "true" and "false", "unknown" as a valid value. In the following, logical values "false", "unknown" and "true" are represented by 0, 1 and 2 respectively.
Let "-" be a unary operator (i.e. a symbol representing one argument function) and let both "*" and "+" be binary operators (i.e. symbols representing two argument functions). These operators represent negation (NOT), conjunction (AND) and disjunction (OR) respectively. These operators in three-valued logic can be defined in Table C-1.
Table C-1: Truth tables of three-valued logic operators
-X| | (X*Y)| | (X+Y) | <image>| | <image>| | <image> |
---|---|---|---|---|---
Let P, Q and R be variables ranging over three-valued logic values. For a given formula, you are asked to answer the number of triples (P,Q,R) that satisfy the formula, that is, those which make the value of the given formula 2. A formula is one of the following form (X and Y represent formulas).
* Constants: 0, 1 or 2
* Variables: P, Q or R
* Negations: -X
* Conjunctions: (X*Y)
* Disjunctions: (X+Y)
Note that conjunctions and disjunctions of two formulas are always parenthesized.
For example, when formula (P*Q) is given as an input, the value of this formula is 2 when and only when (P,Q,R) is (2,2,0), (2,2,1) or (2,2,2). Therefore, you should output 3.
Input
The input consists of one or more lines. Each line contains a formula. A formula is a string which consists of 0, 1, 2, P, Q, R, -, *, +, (, ). Other characters such as spaces are not contained. The grammar of formulas is given by the following BNF.
<formula> ::= 0 | 1 | 2 | P | Q | R |
-<formula> | (<formula>*<formula>) | (<formula>+<formula>)
All the formulas obey this syntax and thus you do not have to care about grammatical errors. Input lines never exceed 80 characters.
Finally, a line which contains only a "." (period) comes, indicating the end of the input.
Output
You should answer the number (in decimal) of triples (P,Q,R) that make the value of the given formula 2. One line containing the number should be output for each of the formulas, and no other characters should be output.
Sample Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output for the Sample Input
3
11
0
27
0
7
Example
Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output
3
11
0
27
0
7
"Correct Solution:
```
def multi(a, b) :
if a == 0 :
return 0
elif a == 1 :
if b == 0 :
return 0
else :
return 1
else :
return b
def add(a, b) :
if a == 0 :
return b
elif a == 1 :
if b == 2 :
return 2
else :
return 1
else :
return 2
def minus(a) :
return (2 - a)
def calc(l) : # '('、')'のない計算式
l = list(l)
#'-'を計算
i = len(l)-1
while True :
if i < 0 :
break
if l[i] == '-' :
print
l[i] = str(minus(int(l[i+1])))
del l[i+1]
i -= 1
#'*'を計算
i = 0
while True :
if i >= len(l) :
break
if l[i] == '*' :
l[i-1] = str(multi(int(l[i-1]), int(l[i+1])))
del l[i:i+2]
else :
i += 1
#'+'を計算
i = 0
while True :
if i >= len(l) :
break
if l[i] == '+' :
l[i-1] = str(add(int(l[i-1]), int(l[i+1])))
del l[i:i+2]
else :
i += 1
return ''.join(l)
def main(l) :
l = list(l)
while '(' in l :
for i in range(len(l)) :
if l[i] == '(' :
start = i
elif l[i] == ')' :
A = ''.join(l[start+1:i])
del l[start:i+1]
l.insert(start, calc(A))
break
if len(l) != 1 :
l = calc(l)
return ''.join(l)
while True :
input_l = input()
if input_l == '.' :
break
cnt = 0
for p in ['0', '1', '2'] :
for q in ['0', '1', '2'] :
for r in ['0', '1', '2'] :
l = input_l
if 'P' in l :
l = l.replace('P', p)
if 'Q' in l :
l = l.replace('Q', q)
if 'R' in l :
l = l.replace('R', r)
if main(l) == '2' :
cnt += 1
print(cnt)
```
| 7,448 |
Provide a correct Python 3 solution for this coding contest problem.
Three-valued logic is a logic system that has, in addition to "true" and "false", "unknown" as a valid value. In the following, logical values "false", "unknown" and "true" are represented by 0, 1 and 2 respectively.
Let "-" be a unary operator (i.e. a symbol representing one argument function) and let both "*" and "+" be binary operators (i.e. symbols representing two argument functions). These operators represent negation (NOT), conjunction (AND) and disjunction (OR) respectively. These operators in three-valued logic can be defined in Table C-1.
Table C-1: Truth tables of three-valued logic operators
-X| | (X*Y)| | (X+Y) | <image>| | <image>| | <image> |
---|---|---|---|---|---
Let P, Q and R be variables ranging over three-valued logic values. For a given formula, you are asked to answer the number of triples (P,Q,R) that satisfy the formula, that is, those which make the value of the given formula 2. A formula is one of the following form (X and Y represent formulas).
* Constants: 0, 1 or 2
* Variables: P, Q or R
* Negations: -X
* Conjunctions: (X*Y)
* Disjunctions: (X+Y)
Note that conjunctions and disjunctions of two formulas are always parenthesized.
For example, when formula (P*Q) is given as an input, the value of this formula is 2 when and only when (P,Q,R) is (2,2,0), (2,2,1) or (2,2,2). Therefore, you should output 3.
Input
The input consists of one or more lines. Each line contains a formula. A formula is a string which consists of 0, 1, 2, P, Q, R, -, *, +, (, ). Other characters such as spaces are not contained. The grammar of formulas is given by the following BNF.
<formula> ::= 0 | 1 | 2 | P | Q | R |
-<formula> | (<formula>*<formula>) | (<formula>+<formula>)
All the formulas obey this syntax and thus you do not have to care about grammatical errors. Input lines never exceed 80 characters.
Finally, a line which contains only a "." (period) comes, indicating the end of the input.
Output
You should answer the number (in decimal) of triples (P,Q,R) that make the value of the given formula 2. One line containing the number should be output for each of the formulas, and no other characters should be output.
Sample Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output for the Sample Input
3
11
0
27
0
7
Example
Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output
3
11
0
27
0
7
"Correct Solution:
```
# AOJ 1155: How can I satisfy thee? Let me count
# Python3 2018.7.17 bal4u
def term(idx):
x, idx = factor(idx)
op = buf[idx]
y, idx = factor(idx+1);
if op == '*':
if x == 2 and y == 2: x = 2
elif x == 0 or y == 0: x = 0
else: x = 1
else:
if x == 0 and y == 0: x = 0
elif x == 2 or y == 2: x = 2
else: x = 1
return [x, idx]
def factor(idx):
global p, q, r
if buf[idx] == '(': x, idx = term(idx+1)
elif buf[idx] == '-':
x, idx = factor(idx+1)
x = 2-x; idx -= 1
elif '0'<= buf[idx] <='9': x = int(buf[idx])
elif buf[idx] == 'P': x = p
elif buf[idx] == 'Q': x = q
else: x = r
return [x, idx+1]
while True:
buf = list(input())
if buf[0] == '.': break
ans = 0
for p in range(3):
for q in range(3):
for r in range(3):
if factor(0)[0] == 2: ans += 1
print(ans)
```
| 7,449 |
Provide a correct Python 3 solution for this coding contest problem.
Three-valued logic is a logic system that has, in addition to "true" and "false", "unknown" as a valid value. In the following, logical values "false", "unknown" and "true" are represented by 0, 1 and 2 respectively.
Let "-" be a unary operator (i.e. a symbol representing one argument function) and let both "*" and "+" be binary operators (i.e. symbols representing two argument functions). These operators represent negation (NOT), conjunction (AND) and disjunction (OR) respectively. These operators in three-valued logic can be defined in Table C-1.
Table C-1: Truth tables of three-valued logic operators
-X| | (X*Y)| | (X+Y) | <image>| | <image>| | <image> |
---|---|---|---|---|---
Let P, Q and R be variables ranging over three-valued logic values. For a given formula, you are asked to answer the number of triples (P,Q,R) that satisfy the formula, that is, those which make the value of the given formula 2. A formula is one of the following form (X and Y represent formulas).
* Constants: 0, 1 or 2
* Variables: P, Q or R
* Negations: -X
* Conjunctions: (X*Y)
* Disjunctions: (X+Y)
Note that conjunctions and disjunctions of two formulas are always parenthesized.
For example, when formula (P*Q) is given as an input, the value of this formula is 2 when and only when (P,Q,R) is (2,2,0), (2,2,1) or (2,2,2). Therefore, you should output 3.
Input
The input consists of one or more lines. Each line contains a formula. A formula is a string which consists of 0, 1, 2, P, Q, R, -, *, +, (, ). Other characters such as spaces are not contained. The grammar of formulas is given by the following BNF.
<formula> ::= 0 | 1 | 2 | P | Q | R |
-<formula> | (<formula>*<formula>) | (<formula>+<formula>)
All the formulas obey this syntax and thus you do not have to care about grammatical errors. Input lines never exceed 80 characters.
Finally, a line which contains only a "." (period) comes, indicating the end of the input.
Output
You should answer the number (in decimal) of triples (P,Q,R) that make the value of the given formula 2. One line containing the number should be output for each of the formulas, and no other characters should be output.
Sample Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output for the Sample Input
3
11
0
27
0
7
Example
Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output
3
11
0
27
0
7
"Correct Solution:
```
just_len = 60
import re
import collections
NUM = r'(?P<NUM>\d+)'
PLUS = r'(?P<PLUS>\+)'
MINUS = r'(?P<MINUS>-)'
TIMES = r'(?P<TIMES>\*)'
LPAREN = r'(?P<LPAREN>\()'
RPAREN = r'(?P<RPAREN>\))'
WS = r'(?P<WS>\s+)'
master_pattern = re.compile('|'.join((NUM, PLUS, MINUS, TIMES, LPAREN, RPAREN, WS)))
Token = collections.namedtuple('Token', ['type', 'value'])
def generate_tokens(pattern, text):
scanner = pattern.scanner(text)
for m in iter(scanner.match, None):
token = Token(m.lastgroup, m.group())
if token.type != 'WS':
yield token
def minus(x):
if x==0: ans=2
if x==1: ans=1
if x==2: ans=0
return ans
def mult(x,y):
if x==0:
a=0
if x==1:
if y==0: a=0
if y==1: a=1
if y==2: a=1
if x==2:
if y==0: a=0
if y==1: a=1
if y==2: a=2
return a
def add(x,y):
if x==0:
if y==0: a=0
if y==1: a=1
if y==2: a=2
if x==1:
if y==0: a=1
if y==1: a=1
if y==2: a=2
if x==2:
a=2
return a
class ExpressionEvaluator:
def parse(self, text):
self.tokens = generate_tokens(master_pattern, text)
self.current_token = None
self.next_token = None
self._advance()
# expr is the top level grammar. So we invoke that first.
# it will invoke other function to consume tokens according to grammar rule.
return self.expr()
def _advance(self):
self.current_token, self.next_token = self.next_token, next(self.tokens, None)
def _accept(self, token_type):
# if there is next token and token type matches
if self.next_token and self.next_token.type == token_type:
self._advance()
return True
else:
return False
def _expect(self, token_type):
if not self._accept(token_type):
raise SyntaxError('Expected ' + token_type)
def expr(self):
'''
expression ::= term { ( +|-) term } *
'''
expr_value = self.term()
while self._accept('PLUS') or self._accept('MINUS'):
op = self.current_token.type
right = self.term()
if op == 'PLUS':
#expr_value += right
expr_value = add(expr_value, right)
elif op == 'MINUS':
#expr_value -= right
expr_value = add(expr_value, minus(right))
else:
raise SyntaxError('Should not arrive here ' + op)
return expr_value
def term(self):
'''
term ::= factor { ('*') factor } *
'''
term_value = self.factor()
while self._accept('TIMES') or self._accept('DIVIDE'):
op = self.current_token.type
if op == 'TIMES':
#term_value *= self.factor()
term_value = mult(term_value, self.factor())
else:
raise SyntaxError('Should not arrive here ' + op)
return term_value
def factor(self):
'''
factor ::= NUM | (expr) | -(factor)
'''
# it can be a number
if self._accept('NUM'):
expr_value = int(self.current_token.value)
# or (expr)
elif self._accept('LPAREN'):
expr_value = self.expr()
self._expect('RPAREN')
elif self._accept('MINUS'):
expr_value = minus(self.factor())
else:
raise SyntaxError('Expect NUMBER or LPAREN')
return expr_value
e = ExpressionEvaluator()
# print('parse 2'.ljust(just_len),
# e.parse('2'))
#
# print('parse 2 + 3'.ljust(just_len),
# e.parse('2 + 3'))
# print('parse 2 + 3 * 4'.ljust(just_len),
# e.parse('2 + 3 * 4'))
#
# print('parse (2 + 3) * 4'.ljust(just_len),
# e.parse('(2 + 3) * 4'))
while True:
rS=input()
if rS=='.': break
ans=0
for p in range(3):
for q in range(3):
for r in range(3):
S = rS.replace('P',str(p))\
.replace('Q',str(q))\
.replace('R',str(r))
if e.parse(S)==2: ans+=1
print(ans)
```
| 7,450 |
Provide a correct Python 3 solution for this coding contest problem.
Three-valued logic is a logic system that has, in addition to "true" and "false", "unknown" as a valid value. In the following, logical values "false", "unknown" and "true" are represented by 0, 1 and 2 respectively.
Let "-" be a unary operator (i.e. a symbol representing one argument function) and let both "*" and "+" be binary operators (i.e. symbols representing two argument functions). These operators represent negation (NOT), conjunction (AND) and disjunction (OR) respectively. These operators in three-valued logic can be defined in Table C-1.
Table C-1: Truth tables of three-valued logic operators
-X| | (X*Y)| | (X+Y) | <image>| | <image>| | <image> |
---|---|---|---|---|---
Let P, Q and R be variables ranging over three-valued logic values. For a given formula, you are asked to answer the number of triples (P,Q,R) that satisfy the formula, that is, those which make the value of the given formula 2. A formula is one of the following form (X and Y represent formulas).
* Constants: 0, 1 or 2
* Variables: P, Q or R
* Negations: -X
* Conjunctions: (X*Y)
* Disjunctions: (X+Y)
Note that conjunctions and disjunctions of two formulas are always parenthesized.
For example, when formula (P*Q) is given as an input, the value of this formula is 2 when and only when (P,Q,R) is (2,2,0), (2,2,1) or (2,2,2). Therefore, you should output 3.
Input
The input consists of one or more lines. Each line contains a formula. A formula is a string which consists of 0, 1, 2, P, Q, R, -, *, +, (, ). Other characters such as spaces are not contained. The grammar of formulas is given by the following BNF.
<formula> ::= 0 | 1 | 2 | P | Q | R |
-<formula> | (<formula>*<formula>) | (<formula>+<formula>)
All the formulas obey this syntax and thus you do not have to care about grammatical errors. Input lines never exceed 80 characters.
Finally, a line which contains only a "." (period) comes, indicating the end of the input.
Output
You should answer the number (in decimal) of triples (P,Q,R) that make the value of the given formula 2. One line containing the number should be output for each of the formulas, and no other characters should be output.
Sample Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output for the Sample Input
3
11
0
27
0
7
Example
Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output
3
11
0
27
0
7
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(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 = []
m = {}
def f(s):
k = s
if k in m:
return m[k]
t = set(re.findall(r"\([^()]+\)", s))
while t:
for c in t:
s = s.replace(c, f(c[1:-1]))
t = set(re.findall(r"\([^()]+\)", s))
while '-' in s:
s = s.replace('-1', '1')
s = s.replace('-2', '0')
s = s.replace('-0', '2')
r = s[0]
for i in range(len(s)//2):
if s[i*2+1] == '*':
r = min(r,s[i*2+2])
else:
r = max(r,s[i*2+2])
m[k] = r
return r
while True:
s = S()
if s == '.':
break
tr = 0
for P,Q,R in itertools.product(['0', '1', '2'], repeat=3):
ts = s.replace('P', P)
ts = ts.replace('Q', Q)
ts = ts.replace('R', R)
if f(ts) == '2':
tr += 1
rr.append(tr)
return '\n'.join(map(str, rr))
print(main())
```
| 7,451 |
Provide a correct Python 3 solution for this coding contest problem.
Three-valued logic is a logic system that has, in addition to "true" and "false", "unknown" as a valid value. In the following, logical values "false", "unknown" and "true" are represented by 0, 1 and 2 respectively.
Let "-" be a unary operator (i.e. a symbol representing one argument function) and let both "*" and "+" be binary operators (i.e. symbols representing two argument functions). These operators represent negation (NOT), conjunction (AND) and disjunction (OR) respectively. These operators in three-valued logic can be defined in Table C-1.
Table C-1: Truth tables of three-valued logic operators
-X| | (X*Y)| | (X+Y) | <image>| | <image>| | <image> |
---|---|---|---|---|---
Let P, Q and R be variables ranging over three-valued logic values. For a given formula, you are asked to answer the number of triples (P,Q,R) that satisfy the formula, that is, those which make the value of the given formula 2. A formula is one of the following form (X and Y represent formulas).
* Constants: 0, 1 or 2
* Variables: P, Q or R
* Negations: -X
* Conjunctions: (X*Y)
* Disjunctions: (X+Y)
Note that conjunctions and disjunctions of two formulas are always parenthesized.
For example, when formula (P*Q) is given as an input, the value of this formula is 2 when and only when (P,Q,R) is (2,2,0), (2,2,1) or (2,2,2). Therefore, you should output 3.
Input
The input consists of one or more lines. Each line contains a formula. A formula is a string which consists of 0, 1, 2, P, Q, R, -, *, +, (, ). Other characters such as spaces are not contained. The grammar of formulas is given by the following BNF.
<formula> ::= 0 | 1 | 2 | P | Q | R |
-<formula> | (<formula>*<formula>) | (<formula>+<formula>)
All the formulas obey this syntax and thus you do not have to care about grammatical errors. Input lines never exceed 80 characters.
Finally, a line which contains only a "." (period) comes, indicating the end of the input.
Output
You should answer the number (in decimal) of triples (P,Q,R) that make the value of the given formula 2. One line containing the number should be output for each of the formulas, and no other characters should be output.
Sample Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output for the Sample Input
3
11
0
27
0
7
Example
Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output
3
11
0
27
0
7
"Correct Solution:
```
import re
# and
def and_def(a, b):
return str(min(int(a), int(b)))
# or
def or_def(a, b):
return str(max(int(a), int(b)))
# not
def not_def(a):
return str(2 - int(a))
def match(struct):
if re.fullmatch(r'\-[0,1,2]', struct):
return not_def(struct[-1])
if re.fullmatch(r'[0,1,2]\+[0,1,2]', struct):
return or_def(struct[0], struct[-1])
if re.fullmatch(r'[0,1,2]\*[0,1,2]', struct):
return and_def(struct[0], struct[-1])
if re.fullmatch(r'[0,1,2]', struct):
return struct
if re.fullmatch(r'\([0,1,2]\)', struct):
return struct[1]
return struct
def parse(struct):
tmpstruct = ''
check, minas = False, False
if len(struct) == 1:
return struct
for i in range(len(struct)):
if not check:
if struct[i] == '(':
check = [')', '(']
tmp = 1
num = i
elif struct[i] == '-':
check = ['0', '1', '2', '(']
minas = True
num = i
else:
tmpstruct += struct[i]
else:
if struct[i] in check:
if struct[i] == ')':
tmp -= 1
if not tmp:
if not minas:
tmpstruct += parse(struct[num+1: i])
else:
tmpstruct += not_def(parse(struct[num + 1: i + 1]))
minas = False
check = False
elif struct[i] == '(' and check == ['0', '1', '2', '(']:
check = [')', '(']
tmp = 1
elif struct[i] == '(':
tmp += 1
else:
tmpstruct += not_def(parse(struct[num + 1: i + 1]))
check = False
minas = False
tmpstruct = match(tmpstruct)
return tmpstruct
def change_PQR(string, P, Q, R):
ret = ''
for i in string:
if i == 'P':
ret += str(P)
elif i == 'Q':
ret += str(Q)
elif i == 'R':
ret += str(R)
else:
ret += i
return ret
while True:
struct = input()
if struct == '.':
break
ans = 0
for i in (0, 1, 2):
for j in (0, 1, 2):
for k in (0, 1, 2):
tmpstr = struct
if parse(change_PQR(tmpstr, i, j, k)) == '2':
ans += 1
print(ans)
```
| 7,452 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three-valued logic is a logic system that has, in addition to "true" and "false", "unknown" as a valid value. In the following, logical values "false", "unknown" and "true" are represented by 0, 1 and 2 respectively.
Let "-" be a unary operator (i.e. a symbol representing one argument function) and let both "*" and "+" be binary operators (i.e. symbols representing two argument functions). These operators represent negation (NOT), conjunction (AND) and disjunction (OR) respectively. These operators in three-valued logic can be defined in Table C-1.
Table C-1: Truth tables of three-valued logic operators
-X| | (X*Y)| | (X+Y) | <image>| | <image>| | <image> |
---|---|---|---|---|---
Let P, Q and R be variables ranging over three-valued logic values. For a given formula, you are asked to answer the number of triples (P,Q,R) that satisfy the formula, that is, those which make the value of the given formula 2. A formula is one of the following form (X and Y represent formulas).
* Constants: 0, 1 or 2
* Variables: P, Q or R
* Negations: -X
* Conjunctions: (X*Y)
* Disjunctions: (X+Y)
Note that conjunctions and disjunctions of two formulas are always parenthesized.
For example, when formula (P*Q) is given as an input, the value of this formula is 2 when and only when (P,Q,R) is (2,2,0), (2,2,1) or (2,2,2). Therefore, you should output 3.
Input
The input consists of one or more lines. Each line contains a formula. A formula is a string which consists of 0, 1, 2, P, Q, R, -, *, +, (, ). Other characters such as spaces are not contained. The grammar of formulas is given by the following BNF.
<formula> ::= 0 | 1 | 2 | P | Q | R |
-<formula> | (<formula>*<formula>) | (<formula>+<formula>)
All the formulas obey this syntax and thus you do not have to care about grammatical errors. Input lines never exceed 80 characters.
Finally, a line which contains only a "." (period) comes, indicating the end of the input.
Output
You should answer the number (in decimal) of triples (P,Q,R) that make the value of the given formula 2. One line containing the number should be output for each of the formulas, and no other characters should be output.
Sample Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output for the Sample Input
3
11
0
27
0
7
Example
Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output
3
11
0
27
0
7
Submitted Solution:
```
# -*- coding: utf-8 -*-
from itertools import product
class thee(int):
def __add__(self, that):
return thee(max(int(self), int(that)))
def __mul__(self, that):
return thee(min(int(self), int(that)))
def __neg__(self):
T = [2, 1, 0]
return thee(T[int(self)])
S = input()
while S != ".":
for x in list("012PQR"):
S = S.replace(x, "thee({})".format(x))
ans = 0
for P, Q, R in product(range(3), repeat=3):
ans += 2 == int(eval(S))
print(ans)
S = input()
```
Yes
| 7,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three-valued logic is a logic system that has, in addition to "true" and "false", "unknown" as a valid value. In the following, logical values "false", "unknown" and "true" are represented by 0, 1 and 2 respectively.
Let "-" be a unary operator (i.e. a symbol representing one argument function) and let both "*" and "+" be binary operators (i.e. symbols representing two argument functions). These operators represent negation (NOT), conjunction (AND) and disjunction (OR) respectively. These operators in three-valued logic can be defined in Table C-1.
Table C-1: Truth tables of three-valued logic operators
-X| | (X*Y)| | (X+Y) | <image>| | <image>| | <image> |
---|---|---|---|---|---
Let P, Q and R be variables ranging over three-valued logic values. For a given formula, you are asked to answer the number of triples (P,Q,R) that satisfy the formula, that is, those which make the value of the given formula 2. A formula is one of the following form (X and Y represent formulas).
* Constants: 0, 1 or 2
* Variables: P, Q or R
* Negations: -X
* Conjunctions: (X*Y)
* Disjunctions: (X+Y)
Note that conjunctions and disjunctions of two formulas are always parenthesized.
For example, when formula (P*Q) is given as an input, the value of this formula is 2 when and only when (P,Q,R) is (2,2,0), (2,2,1) or (2,2,2). Therefore, you should output 3.
Input
The input consists of one or more lines. Each line contains a formula. A formula is a string which consists of 0, 1, 2, P, Q, R, -, *, +, (, ). Other characters such as spaces are not contained. The grammar of formulas is given by the following BNF.
<formula> ::= 0 | 1 | 2 | P | Q | R |
-<formula> | (<formula>*<formula>) | (<formula>+<formula>)
All the formulas obey this syntax and thus you do not have to care about grammatical errors. Input lines never exceed 80 characters.
Finally, a line which contains only a "." (period) comes, indicating the end of the input.
Output
You should answer the number (in decimal) of triples (P,Q,R) that make the value of the given formula 2. One line containing the number should be output for each of the formulas, and no other characters should be output.
Sample Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output for the Sample Input
3
11
0
27
0
7
Example
Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output
3
11
0
27
0
7
Submitted Solution:
```
class N:
def __init__(self, a):
self.a = a
def __mul__(self, b):
if self.a == 0:
return N(0)
elif self.a == 1:
return N((b.a >= 1) * 1)
else:
return b
def __add__(self, b):
if self.a == 0:
return b
elif self.a == 1:
return N((b.a > 1) + 1)
else:
return N(2)
def __neg__(self):
if self.a == 2:
return N(0)
elif self.a == 1:
return N(1)
else:
return N(2)
while True:
s = input().replace("-", "-").replace("0", "N(0)").replace("1", "N(1)").replace("2", "N(2)")
N(1) + N(2)
if s == ".": break
result = []
for P in map(N, range(3)):
for Q in map(N, range(3)):
for R in map(N, range(3)):
result.append(eval(s).a)
print(result.count(2))
```
Yes
| 7,454 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three-valued logic is a logic system that has, in addition to "true" and "false", "unknown" as a valid value. In the following, logical values "false", "unknown" and "true" are represented by 0, 1 and 2 respectively.
Let "-" be a unary operator (i.e. a symbol representing one argument function) and let both "*" and "+" be binary operators (i.e. symbols representing two argument functions). These operators represent negation (NOT), conjunction (AND) and disjunction (OR) respectively. These operators in three-valued logic can be defined in Table C-1.
Table C-1: Truth tables of three-valued logic operators
-X| | (X*Y)| | (X+Y) | <image>| | <image>| | <image> |
---|---|---|---|---|---
Let P, Q and R be variables ranging over three-valued logic values. For a given formula, you are asked to answer the number of triples (P,Q,R) that satisfy the formula, that is, those which make the value of the given formula 2. A formula is one of the following form (X and Y represent formulas).
* Constants: 0, 1 or 2
* Variables: P, Q or R
* Negations: -X
* Conjunctions: (X*Y)
* Disjunctions: (X+Y)
Note that conjunctions and disjunctions of two formulas are always parenthesized.
For example, when formula (P*Q) is given as an input, the value of this formula is 2 when and only when (P,Q,R) is (2,2,0), (2,2,1) or (2,2,2). Therefore, you should output 3.
Input
The input consists of one or more lines. Each line contains a formula. A formula is a string which consists of 0, 1, 2, P, Q, R, -, *, +, (, ). Other characters such as spaces are not contained. The grammar of formulas is given by the following BNF.
<formula> ::= 0 | 1 | 2 | P | Q | R |
-<formula> | (<formula>*<formula>) | (<formula>+<formula>)
All the formulas obey this syntax and thus you do not have to care about grammatical errors. Input lines never exceed 80 characters.
Finally, a line which contains only a "." (period) comes, indicating the end of the input.
Output
You should answer the number (in decimal) of triples (P,Q,R) that make the value of the given formula 2. One line containing the number should be output for each of the formulas, and no other characters should be output.
Sample Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output for the Sample Input
3
11
0
27
0
7
Example
Input
(P*Q)
(--R+(P*Q))
(P*-P)
2
1
(-1+(((---P+Q)*(--Q+---R))*(-R+-P)))
.
Output
3
11
0
27
0
7
Submitted Solution:
```
from collections import deque
def AND(a, b):
if a == "0" or b == "0":
return "0"
elif a == b == "2":
return "2"
else:
return "1"
def OR(a, b):
if a == "2" or b == "2":
return 2
elif a == b == "0":
return "0"
else:
return "1"
def NOT(a):
if a.count("-") % 2 == 1:
if a[0] == "0":
return "2"
elif a[0] == "2":
return "0"
else:
return "1"
else:
return a[0]
def solve(S):
que = deque()
for s in S:
if s == ")":
formula = ""
while True:
q = que.pop()
if q == "(":
break
formula += q
if "+" in formula:
a, b = formula.split("+")
a = NOT(a)
b = NOT(b)
que.append(str(OR(a, b)))
if "*" in formula:
a, b = formula.split("*")
a = NOT(a)
b = NOT(b)
que.append(str(AND(a, b)))
else:
que.append(s)
return NOT("".join(reversed(que)))
while True:
S = input()
if S == ".":
break
count = 0
for p in range(3):
for q in range(3):
for r in range(3):
if solve(S.replace("P", str(p)).replace("Q", str(q)).replace("R", str(r))) == "2":
count += 1
print(count)
```
Yes
| 7,455 |
Provide a correct Python 3 solution for this coding contest problem.
Despite urging requests of the townspeople, the municipal office cannot afford to improve many of the apparently deficient city amenities under this recession. The city swimming pool is one of the typical examples. It has only two swimming lanes. The Municipal Fitness Agency, under this circumstances, settled usage rules so that the limited facilities can be utilized fully.
Two lanes are to be used for one-way swimming of different directions. Swimmers are requested to start swimming in one of the lanes, from its one end to the other, and then change the lane to swim his/her way back. When he or she reaches the original starting end, he/she should return to his/her initial lane and starts swimming again.
Each swimmer has his/her own natural constant pace. Swimmers, however, are not permitted to pass other swimmers except at the ends of the pool; as the lanes are not wide enough, that might cause accidents. If a swimmer is blocked by a slower swimmer, he/she has to follow the slower swimmer at the slower pace until the end of the lane is reached. Note that the blocking swimmer’s natural pace may be faster than the blocked swimmer; the blocking swimmer might also be blocked by another swimmer ahead, whose natural pace is slower than the blocked swimmer. Blocking would have taken place whether or not a faster swimmer was between them.
Swimmers can change their order if they reach the end of the lane simultaneously. They change their order so that ones with faster natural pace swim in front. When a group of two or more swimmers formed by a congestion reaches the end of the lane, they are considered to reach there simultaneously, and thus change their order there.
The number of swimmers, their natural paces in times to swim from one end to the other, and the numbers of laps they plan to swim are given. Note that here one "lap" means swimming from one end to the other and then swimming back to the original end. Your task is to calculate the time required for all the swimmers to finish their plans. All the swimmers start from the same end of the pool at the same time, the faster swimmers in front.
In solving this problem, you can ignore the sizes of swimmers' bodies, and also ignore the time required to change the lanes and the order in a group of swimmers at an end of the lanes.
Input
The input is a sequence of datasets. Each dataset is formatted as follows.
n
t1 c1
...
tn cn
n is an integer (1 ≤ n ≤ 50) that represents the number of swimmers. ti and ci are integers (1 ≤ ti ≤ 300, 1 ≤ ci ≤ 250) that represent the natural pace in times to swim from one end to the other and the number of planned laps for the i-th swimmer, respectively. ti and ci are separated by a space.
The end of the input is indicated by a line containing one zero.
Output
For each dataset, output the time required for all the swimmers to finish their plans in a line. No extra characters should occur in the output.
Example
Input
2
10 30
15 20
2
10 240
15 160
3
2 6
7 2
8 2
4
2 4
7 2
8 2
18 1
0
Output
600
4800
36
40
"Correct Solution:
```
from collections import deque
while 1:
N = int(input())
if N == 0:
break
T = [0]*N; C = [0]*N
que0 = deque()
que1 = deque()
P = [list(map(int, input().split())) for i in range(N)]
P.sort()
for i in range(N):
t, c = P[i]
que0.append((i, t))
T[i] = t
C[i] = c
INF = 10**18
ans = 0
rest = N
while rest:
t = min(que0[0][1] if que0 else INF, que1[0][1] if que1 else INF)
st0 = []; st1 = []
while que0 and que0[0][1] <= t:
st0.append(que0.popleft()[0])
st0.sort()
for i in st0:
que1.append((i, t+T[i]))
while que1 and que1[0][1] <= t:
st1.append(que1.popleft()[0])
st1.sort()
for i in st1:
if C[i] == 1:
rest -= 1
else:
que0.append((i, t+T[i]))
C[i] -= 1
ans = max(ans, t)
print(ans)
```
| 7,456 |
Provide a correct Python 3 solution for this coding contest problem.
Despite urging requests of the townspeople, the municipal office cannot afford to improve many of the apparently deficient city amenities under this recession. The city swimming pool is one of the typical examples. It has only two swimming lanes. The Municipal Fitness Agency, under this circumstances, settled usage rules so that the limited facilities can be utilized fully.
Two lanes are to be used for one-way swimming of different directions. Swimmers are requested to start swimming in one of the lanes, from its one end to the other, and then change the lane to swim his/her way back. When he or she reaches the original starting end, he/she should return to his/her initial lane and starts swimming again.
Each swimmer has his/her own natural constant pace. Swimmers, however, are not permitted to pass other swimmers except at the ends of the pool; as the lanes are not wide enough, that might cause accidents. If a swimmer is blocked by a slower swimmer, he/she has to follow the slower swimmer at the slower pace until the end of the lane is reached. Note that the blocking swimmer’s natural pace may be faster than the blocked swimmer; the blocking swimmer might also be blocked by another swimmer ahead, whose natural pace is slower than the blocked swimmer. Blocking would have taken place whether or not a faster swimmer was between them.
Swimmers can change their order if they reach the end of the lane simultaneously. They change their order so that ones with faster natural pace swim in front. When a group of two or more swimmers formed by a congestion reaches the end of the lane, they are considered to reach there simultaneously, and thus change their order there.
The number of swimmers, their natural paces in times to swim from one end to the other, and the numbers of laps they plan to swim are given. Note that here one "lap" means swimming from one end to the other and then swimming back to the original end. Your task is to calculate the time required for all the swimmers to finish their plans. All the swimmers start from the same end of the pool at the same time, the faster swimmers in front.
In solving this problem, you can ignore the sizes of swimmers' bodies, and also ignore the time required to change the lanes and the order in a group of swimmers at an end of the lanes.
Input
The input is a sequence of datasets. Each dataset is formatted as follows.
n
t1 c1
...
tn cn
n is an integer (1 ≤ n ≤ 50) that represents the number of swimmers. ti and ci are integers (1 ≤ ti ≤ 300, 1 ≤ ci ≤ 250) that represent the natural pace in times to swim from one end to the other and the number of planned laps for the i-th swimmer, respectively. ti and ci are separated by a space.
The end of the input is indicated by a line containing one zero.
Output
For each dataset, output the time required for all the swimmers to finish their plans in a line. No extra characters should occur in the output.
Example
Input
2
10 30
15 20
2
10 240
15 160
3
2 6
7 2
8 2
4
2 4
7 2
8 2
18 1
0
Output
600
4800
36
40
"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 = [LI() for _ in range(n)]
q = []
d = [0] * 2
for t,c in a:
heapq.heappush(q, (0,0,t,c*2))
while q:
ct, l, t, c = heapq.heappop(q)
nx = l ^ 1
nt = ct + t
if d[nx] > nt:
nt = d[nx]
else:
d[nx] = nt
if c > 1:
heapq.heappush(q, (nt,nx,t,c-1))
return max(d)
while 1:
n = I()
if n == 0:
break
rr.append(f(n))
return '\n'.join(map(str, rr))
print(main())
```
| 7,457 |
Provide a correct Python 3 solution for this coding contest problem.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
"Correct Solution:
```
import sys
sys.setrecursionlimit(1000000)
while True:
w, h = map(int, input().split())
if w == 0:
break
mp = ["X" + input() + "X" for _ in range(h)]
mp.insert(0, "X" * (w + 2))
mp.append("X" * (w + 2))
visited_w = [[False] * (w + 2) for _ in range(h + 2)]
visited_b = [[False] * (w + 2) for _ in range(h + 2)]
vec = ((0, 1), (0, -1), (1, 0), (-1, 0))
def search(x, y, visited):
for dx, dy in vec:
nx, ny = x + dx, y + dy
if not visited[ny][nx] and mp[ny][nx] == ".":
visited[ny][nx] = True
search(nx, ny, visited)
for y in range(1, h + 1):
for x in range(1, w + 1):
if mp[y][x] == "W":
search(x, y, visited_w)
elif mp[y][x] == "B":
search(x, y, visited_b)
ans_w = ans_b = 0
for y in range(1, h + 1):
for x in range(1, w + 1):
if visited_w[y][x] and not visited_b[y][x]:
ans_w += 1
elif not visited_w[y][x] and visited_b[y][x]:
ans_b += 1
print(ans_b, ans_w)
```
| 7,458 |
Provide a correct Python 3 solution for this coding contest problem.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
"Correct Solution:
```
import sys
from collections import Counter
sys.setrecursionlimit(2502)
def paint(field, i, j, b, f, moves={(-1, 0), (1, 0), (0, 1), (0, -1)}):
fij = field[i][j]
if fij & f:
return
if fij & 4 and not fij & b:
return
field[i][j] |= b | f
for di, dj in moves:
ni = i + di
nj = j + dj
if nj < 0 or w <= nj or ni < 0 or h <= ni:
continue
paint(field, ni, nj, b, f)
buf = []
chardict = {'.': 0, 'W': 5, 'B': 6}
while True:
w, h = map(int, input().split())
if w == 0:
break
field = [[chardict[c] for c in input()] for _ in range(h)]
for i in range(h):
for j in range(w):
fij = field[i][j]
if fij & 4 and not fij & 24:
paint(field, i, j, fij & 3, (fij & 3) << 3)
result = Counter(b & 7 for row in field for b in row)
buf.append('{} {}'.format(result[2], result[1]))
print('\n'.join(buf))
```
| 7,459 |
Provide a correct Python 3 solution for this coding contest problem.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
"Correct Solution:
```
import sys
sys.setrecursionlimit(3000)
def dfs(r, c, n):
board[r][c] = n
drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
for dr, dc in drc:
nr, nc = r + dr, c + dc
if 0 <= nr < h and 0 <= nc < w and board[nr][nc] != n:
if board[nr][nc] in 'WB':
pile.append(board[nr][nc])
continue
dfs(nr, nc, n)
while True:
w, h = map(int, input().split())
if w == 0 and h == 0: break
board = [list(input()) for _ in range(h)]
place = 0
piles = []
black, white = [], []
for r in range(h):
for c in range(w):
if board[r][c] == '.':
pile = []
place += 1
dfs(r, c, place)
piles.append(pile)
for i, pile in enumerate(piles):
if not pile: continue
for p in pile:
if p != 'B':
break
else:
black.append(i+1)
for p in pile:
if p != 'W':
break
else:
white.append(i+1)
ans_b, ans_w = 0, 0
for row in board:
for c in row:
if c in black:
ans_b += 1
elif c in white:
ans_w += 1
print(ans_b, ans_w)
```
| 7,460 |
Provide a correct Python 3 solution for this coding contest problem.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
"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 dfs(x,y):
global st
global visited
global ans
if MAP[y][x] == '#':
ans |= 0
return
elif MAP[y][x] == 'B':
ans |= 1
return
elif MAP[y][x] == 'W':
ans |= 2
return
else:
visited[y][x] = True
st.add((x,y))
if not visited[y][x+1]:
dfs(x+1,y)
if not visited[y][x-1]:
dfs(x-1,y)
if not visited[y+1][x]:
dfs(x,y+1)
if not visited[y-1][x]:
dfs(x,y-1)
return
while True:
W,H = inpl()
if W == 0:
break
else:
MAP = []
MAP.append(['#']*(W+2))
for _ in range(H):
MAP.append(['#']+list(input())+['#'])
MAP.append(['#']*(W+2))
visited = [[False]*(W+2) for _ in range(H+2)]
dp = [[-1]*(W+2) for _ in range(H+2)]
ansb = answ = 0
for y0 in range(1,H+1):
for x0 in range(1,W+1):
if not visited[y0][x0]:
st = set([])
ans = 0
dfs(x0,y0)
for x,y in st:
dp[y][x] = ans
#for d in dp:
# print(' '.join([str(k).rjust(2) for k in d]))
answ = ansb = 0
for d in dp:
answ += d.count(2)
ansb += d.count(1)
print(ansb,answ)
```
| 7,461 |
Provide a correct Python 3 solution for this coding contest problem.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
"Correct Solution:
```
# coding: utf-8
import queue
while 1:
w,h=map(int,input().split())
if w==0:
break
field=[]
for i in range(h):
field.append(list(input()))
B=0
W=0
for i in range(h):
for j in range(w):
if field[i][j]=='.':
q=queue.Queue()
q.put((i,j))
check=set()
d=0
while not q.empty():
y,x=q.get()
if field[y][x]=='.':
field[y][x]='#'
d+=1
elif field[y][x]=='W':
check.add('W')
continue
elif field[y][x]=='B':
check.add('B')
continue
else:
continue
if 0<=y+1<h and 0<=x<w:
q.put((y+1,x))
if 0<=y-1<h and 0<=x<w:
q.put((y-1,x))
if 0<=y<h and 0<=x+1<w:
q.put((y,x+1))
if 0<=y<h and 0<=x-1<w:
q.put((y,x-1))
if len(check)==2:
pass
elif 'B' in check:
B+=d
elif 'W' in check:
W+=d
print(B,W)
```
| 7,462 |
Provide a correct Python 3 solution for this coding contest problem.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
"Correct Solution:
```
from collections import deque
dxs = [1,0,-1,0]
dys = [0,1,0,-1]
def bfs(x,y,c):
q = deque([(x,y)])
while q:
x,y = q.popleft()
for dx,dy in zip(dxs,dys):
nx,ny = x+dx,y+dy
if nx < 0 or nx >= W or ny < 0 or ny >= H: continue
if src[ny][nx] != '.' or mem[c][ny][nx]: continue
q.append((nx,ny))
mem[c][ny][nx] = 1
while True:
W,H = map(int,input().split())
if W == 0: break
src = [input() for i in range(H)]
mem = [[[0 for w in range(W)] for h in range(H)] for c in range(2)]
for y in range(H):
for x in range(W):
if src[y][x] == '.': continue
c = (0 if src[y][x] == 'B' else 1)
bfs(x,y,c)
b = w = 0
for y in range(H):
for x in range(W):
bm,wm = mem[0][y][x], mem[1][y][x]
if bm and not wm: b += 1
elif wm and not bm: w += 1
print(str(b) + ' ' + str(w))
```
| 7,463 |
Provide a correct Python 3 solution for this coding contest problem.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
"Correct Solution:
```
import sys
sys.setrecursionlimit(1000000)
while True:
w,h=map(int,input().split())
if w==0:
break
mp=["X"+input()+"X" for _ in range(h)]
mp.insert(0,"X"*(w+2))
mp.append('X'*(w+2))
visited_w=[[False]*(w+2) for _ in range(h+2)]
visited_b=[[False]*(w+2) for _ in range(h+2)]
vec=((0,1),(0,-1),(1,0),(-1,0))
def search(x,y,visited):
for dx, dy in vec:
nx,ny=x+dx,y+dy
if not visited[ny][nx] and mp[ny][nx]==".":
visited[ny][nx]=True
search(nx,ny,visited)
for y in range(1,h+1):
for x in range(1,w+1):
if mp[y][x]=="W":
search(x,y,visited_w)
elif mp[y][x]=="B":
search(x,y,visited_b)
ans_w=ans_b=0
for y in range(1,h+1):
for x in range(1,w+1):
if visited_w[y][x] and not visited_b[y][x]:
ans_w +=1
elif not visited_w[y][x] and visited_b[y][x]:
ans_b+=1
print(ans_b,ans_w)
```
| 7,464 |
Provide a correct Python 3 solution for this coding contest problem.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
"Correct Solution:
```
import sys
from collections import Counter
sys.setrecursionlimit(2502)
def paint(field, i, j, b, f, moves={(-1, 0), (1, 0), (0, 1), (0, -1)}):
fij = field[i][j]
if fij & f:
return
if fij & 4 and not fij & b:
return
field[i][j] |= b | f
for di, dj in moves:
ni = i + di
nj = j + dj
if nj < 0 or w <= nj or ni < 0 or h <= ni:
continue
paint(field, ni, nj, b, f)
buf = []
chardict = {'.': 0, 'W': 5, 'B': 6}
while True:
w, h = map(int, input().split())
if w == 0:
break
field = []
init_w, init_b = 0, 0
for _ in range(h):
line = input().strip()
init_w += line.count('W')
init_b += line.count('B')
field.append([chardict[c] for c in line])
for i in range(h):
for j in range(w):
fij = field[i][j]
if fij & 4 and not fij & 24:
paint(field, i, j, fij & 3, (fij & 3) << 3)
result = Counter(b & 3 for row in field for b in row)
print(result[2] - init_b, result[1] - init_w)
```
| 7,465 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
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 = []
d = [(0,1),(0,-1),(1,0),(-1,0)]
while True:
w,h = LI()
if w == 0 and h == 0:
break
a = [S() for _ in range(h)]
b = [[0]*w for _ in range(h)]
c = [[0]*w for _ in range(h)]
q = []
for i in range(h):
for j in range(w):
if a[i][j] == 'B':
q.append((i,j))
qi = 0
f = [[None]*w for _ in range(h)]
while len(q) > qi:
i,j = q[qi]
qi += 1
for di,dj in d:
ni = di + i
nj = dj + j
if 0 <= ni < h and 0 <= nj < w and f[ni][nj] is None:
f[ni][nj] = 1
if a[ni][nj] == '.':
q.append((ni,nj))
b[ni][nj] = 1
q = []
for i in range(h):
for j in range(w):
if a[i][j] == 'W':
q.append((i,j))
qi = 0
f = [[None]*w for _ in range(h)]
while len(q) > qi:
i,j = q[qi]
qi += 1
for di,dj in d:
ni = di + i
nj = dj + j
if 0 <= ni < h and 0 <= nj < w and f[ni][nj] is None:
f[ni][nj] = 1
if a[ni][nj] == '.':
q.append((ni,nj))
c[ni][nj] = 1
bc = wc = 0
for i in range(h):
for j in range(w):
if b[i][j] == 1 and c[i][j] == 0:
bc += 1
elif c[i][j] == 1 and b[i][j] == 0:
wc += 1
rr.append('{} {}'.format(bc,wc))
return '\n'.join(map(str, rr))
print(main())
```
Yes
| 7,466 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
Submitted Solution:
```
def bfs(i, j):
if a[i][j] == ".":
a[i][j] = "#"
res=1
wc=0
bc=0
for dy in range(-1, 2):
for dx in range(-1, 2):
if (dx==0 and dy!=0) or (dx!=0 and dy==0):
pass
else:
continue
ny = i+dy
nx = j+dx
if 0<=nx<=w-1 and 0<=ny<=h-1 and a[ny][nx]!="#":
if a[ny][nx] == ".":
wct, bct, rest = bfs(ny, nx)
wc+=wct
bc+=bct
res+=rest
elif a[ny][nx]=="W":
wc+=1
elif a[ny][nx]=="B":
bc+=1
#print(wc, bc, res)
return wc, bc, res
import sys
sys.setrecursionlimit(100000)
while True:
w, h = map(int, input().split())
wans = 0
bans = 0
if w==0 and h==0:
break
a = [list(input()) for _ in range(h)]
for i in range(w):
for j in range(h):
if a[j][i] ==".":
wc, bc, res = bfs(j, i)
if wc>0 and bc==0:
wans+=res
elif wc==0 and bc>0:
bans+=res
print(bans, wans)
```
Yes
| 7,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
Submitted Solution:
```
from collections import deque
def bfs(y,x):
q = deque()
q.append((y,x))
bfs_map[y][x] = 0
res = 0
su = 1
while q:
y,x = q.popleft()
for dy,dx in d:
y_ = y+dy
x_ = x+dx
if 0 <= y_ < h and 0 <= x_ < w:
res |= f[s[y_][x_]]
if bfs_map[y_][x_]:
bfs_map[y_][x_] = 0
if not f[s[y_][x_]]:
q.append((y_,x_))
su += 1
return res,su
d = [(1,0),(-1,0),(0,1),(0,-1)]
while 1:
w,h = map(int, input().split())
if w == h == 0:
break
s = [input() for i in range(h)]
bfs_map = [[1 for j in range(w)] for i in range(h)]
f = {".":0, "B":1, "W":2}
ans = [0,0,0,0]
for y in range(h):
for x in range(w):
if bfs_map[y][x] and s[y][x] == ".":
k,su = bfs(y,x)
ans[k] += su
print(*ans[1:3])
```
Yes
| 7,468 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
Submitted Solution:
```
from collections import deque
dxy = [[0, 1], [1, 0], [-1, 0], [0, -1]]
def which(x, y, map):
if(map[x][y] != "." ):
return (True, 0)
else:
Q = deque()
W, H = len(map[0]), len(map)
map[x][y] = "#"
Q.append((x, y))
# 0は未定,1なら黒、2なら白, 3は無効
Black, White = False, False
res = 1
while(len(Q) != 0):
now = Q.popleft()
for d in dxy:
tx, ty = now[0]+d[0], now[1]+d[1]
# 色判定もする
if 0 <= tx <= H-1 and 0 <= ty <= W-1:
if map[tx][ty] == ".":
map[tx][ty] = "#"
res += 1
Q.append((tx, ty))
elif map[tx][ty] == "B":
Black = True
elif map[tx][ty] == "W":
White = True
# 黒かどうかと、レス、無効ならTrue 0
return (Black, res) if Black ^ White else (True, 0)
while(True):
# .だけBFSする、Wにしかぶつからないで全部いけたらW
W, H = [int(n) for n in input().split()]
V = [[False for _ in range(W)]for __ in range(H)]
if W+H == 0:
break
map = ["" for _ in range(H)]
for i in range(H):
map[i] = list(str(input()))
b = 0
w = 0
for i in range(H):
for j in range(W):
Black, cnt = which(i, j, map)
if Black:
b += cnt
else:
w += cnt
# for i in range(H):
# print(map[i])
print(b, w)
```
Yes
| 7,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
Submitted Solution:
```
def dfs(r, c, n):
if board[r][c] == n:
return
if board[r][c] in 'WB':
pile.append(board[r][c])
return
board[r][c] = n
drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
for dr, dc in drc:
nr, nc = r + dr, c + dc
if 0 <= nr < h and 0 <= nc < w:
dfs(nr, nc, n)
while True:
w, h = map(int, input().split())
if w == 0 and h == 0: break
board = [list(input()) for _ in range(h)]
place = 0
piles = []
black, white = [], []
for r in range(h):
for c in range(w):
if board[r][c] == '.':
pile = []
place += 1
dfs(r, c, place)
piles.append(pile)
for i, pile in enumerate(piles):
if not pile: continue
for p in pile:
if p != 'B':
break
else:
black.append(i+1)
for p in pile:
if p != 'W':
break
else:
white.append(i+1)
ans_b, ans_w = 0, 0
for row in board:
for c in row:
if c in black:
ans_b += 1
elif c in white:
ans_w += 1
print(ans_b, ans_w)
```
No
| 7,470 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
Submitted Solution:
```
import sys
sys.setrecursionlimit(3000)
def dfs(r, c, n):
board[r][c] = n
drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
for dr, dc in drc:
nr, nc = r + dr, c + dc
if 0 <= nr < h and 0 <= nc < w and board[nr][nc] != n:
if board[nr][nc] in 'WB':
pile.append(board[nr][nc])
continue
dfs(nr, nc, n)
while True:
w, h = map(int, input().split())
if w == 0 and h == 0: break
board = [list(input()) for _ in range(h)]
place = 0
piles = []
black, white = [], []
for r in range(h):
for c in range(w):
if board[r][c] == '.':
pile = []
place += 1
dfs(r, c, place)
piles.append(pile)
for i, pile in enumerate(piles):
if not pile: continue
if all(p == 'B' for p in pile):
black.append(i)
elif all(p == 'W' for p in pile):
white.append(i)
ans_b, ans_w = 0, 0
for row in board:
for c in row:
if c in black:
ans_b += 1
elif c in white:
ans_w += 1
print(ans_b, ans_w)
```
No
| 7,471 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
Submitted Solution:
```
from collections import Counter
def paint(field, i, j, b, f, moves={(-1, 0), (1, 0), (0, 1), (0, -1)}):
fij = field[i][j]
if fij & f:
return
if fij & 4 and not fij & b:
return
field[i][j] |= b | f
for di, dj in moves:
ni = i + di
nj = j + dj
if nj < 0 or w <= nj or ni < 0 or h <= ni:
continue
paint(field, ni, nj, b, f)
buf = []
chardict = {'.': 0, 'W': 5, 'B': 6}
while True:
w, h = map(int, input().split())
if w == 0:
break
field = []
init_w, init_b = 0, 0
for _ in range(h):
line = input().strip()
init_w += line.count('W')
init_b += line.count('B')
field.append([chardict[c] for c in line])
for i in range(h):
for j in range(w):
fij = field[i][j]
if fij & 4 and not fij & 24:
paint(field, i, j, fij & 3, (fij & 3) << 3)
result = Counter(b & 3 for row in field for b in row)
print(result[2] - init_b, result[1] - init_w)
```
No
| 7,472 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Surrounding Area
Land fence
English text is not available in this practice contest.
Two real estate agents were boarding a passenger ship to the southern island. Blue sky, refreshing breeze ... The two enjoyed a voyage with other passengers. However, one day a tornado suddenly sank a passenger ship. The other passengers were rescued by the rescue team, but somehow only these two were overlooked. After a few days of drifting, they landed on an uninhabited island. This uninhabited island was rectangular and was divided into grids as shown in the figure below.
Shape of uninhabited island
Figure C-1: Shape of uninhabited island
They were so greedy that they were thinking of selling the land on this uninhabited island rather than calling for help. And they did not split the land in half, but began to scramble for the land. They each began to enclose what they wanted to land on one with black stakes and the other with white stakes. All stakes were struck in the center of the grid, and no stakes were struck in one grid. After a while, both were exhausted and stopped hitting the stakes.
Your job is to write a program to find the area of land surrounded by black and white stakes. However, it is intuitive that the grid (i, j) is surrounded by black stakes. It means that. To be exact, it is defined as follows.
> Define a grid "extended adjacent" to the black stake as follows: The same applies to white stakes.
>
> * If there are no stakes in grid (i, j) and there are black stakes in any of the grids adjacent to grid (i, j), then grid (i, j) extends adjacent to the black stakes. doing.
>
> * If there are no stakes in grid (i, j) and any of the grids adjacent to grid (i, j) are extended adjacent to black stakes, then grid (i, j) is a black stake. It is adjacent to the stake. This rule is applied recursively.
>
>
>
> At this time, when the grid (i, j) is extended adjacent to the black stake and not adjacent to the white stake, and only then, the grid (i, j) is surrounded by the black stake. It is said that there is. Conversely, when the grid (i, j) is extended adjacent to the white stake and not adjacent to the black stake, and only then, the grid (i, j) is surrounded by the white stake. It is said that there is.
Input
The input consists of multiple datasets. Each data set has the following structure.
> w h
> a1,1 a2,1 a3,1 ... aw,1
> a1,2 a2,2 a3,2 ... aw, 2
> ...
> a1, h a2, h a3, h ... aw, h
w is the width of the land and h is the height of the land. These satisfy 1 ≤ w and h ≤ 50. Each ai, j is one half-width character representing the state of the grid (i, j), "` B` "is struck with a black stake, and" `W`" is struck with a white stake. "`.` "(Period) indicates that none of the stakes have been struck.
w = h = 0 represents the end of the input and is not included in the dataset.
Output
For each dataset, print the size of the land surrounded by the black stakes and the size of the land surrounded by the white stakes on one line, separated by a single space.
Sample Input
10 10
..... W ....
.... W.W ...
... W ... W ..
.... W ... W.
..... W ... W
...... W.W.
BBB .... W ..
..B..BBBBB
..B .... B ....
..B..B..W.
5 3
... B.
... BB
.....
1 1
..
0 0
Output for the Sample Input
6 21
12 0
0 0
Example
Input
10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0
Output
6 21
12 0
0 0
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def dfs(x, y, symbol,land):
if land[y][x] != '.':
return ([land[y][x]] if not str(land[y][x]).isnumeric() else False), 0
land[y][x] = symbol
count = 1
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
owner_list = []
for dx,dy in dxdy:
if 0 <= x + dx < len(land[0]) and 0 <= y + dy < len(land):
ret,c = dfs(x + dx, y + dy, symbol,land)
count += c
if ret is not False:
owner_list += ret
return (list(set(owner_list)), count)
while True:
w,h = map(int,input().split())
if w == 0 and h == 0:
break
land = [list(input()) for i in range(0,h)]
symbol = 0
count_dict = {'W' :0, 'B' :0}
for y in range(h):
for x in range(w):
if land[y][x] == '.':
ret, count = dfs(x,y,symbol,land)
if len(ret) == 1:
count_dict[ret[0]] += count
symbol += 1
print(count_dict['B'],count_dict['W'])
```
No
| 7,473 |
Provide a correct Python 3 solution for this coding contest problem.
Some of you know an old story of Voronoi Island. There were N liege lords and they are always involved in territorial disputes. The residents of the island were despaired of the disputes.
One day, a clever lord proposed to stop the disputes and divide the island fairly. His idea was to divide the island such that any piece of area belongs to the load of the nearest castle. The method is called Voronoi Division today.
Actually, there are many aspects of whether the method is fair. According to one historian, the clever lord suggested the method because he could gain broader area than other lords.
Your task is to write a program to calculate the size of the area each lord can gain. You may assume that Voronoi Island has a convex shape.
Input
The input consists of multiple datasets. Each dataset has the following format:
N M
Ix1 Iy1
Ix2 Iy2
...
IxN IyN
Cx1 Cy1
Cx2 Cy2
...
CxM CyM
N is the number of the vertices of Voronoi Island; M is the number of the liege lords; (Ixi, Iyi) denotes the coordinate of the i-th vertex; (Cxi, Cyi ) denotes the coordinate of the castle of the i-the lord.
The input meets the following constraints: 3 ≤ N ≤ 10, 2 ≤ M ≤ 10, -100 ≤ Ixi, Iyi, Cxi, Cyi ≤ 100. The vertices are given counterclockwise. All the coordinates are integers.
The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed.
Output
For each dataset, print the area gained by each liege lord with an absolute error of at most 10-4 . You may output any number of digits after the decimal point. The order of the output areas must match that of the lords in the input.
Example
Input
3 3
0 0
8 0
0 8
2 2
4 2
2 4
0 0
Output
9.0
11.5
11.5
"Correct Solution:
```
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def cross3(O, A, B):
ox, oy = O; ax, ay = A; bx, by = B
return (ax - ox) * (by - oy) - (bx - ox) * (ay - oy)
def cross_point(p0, p1, q0, q1):
x0, y0 = p0; x1, y1 = p1
x2, y2 = q0; x3, y3 = q1
dx0 = x1 - x0; dy0 = y1 - y0
dx1 = x3 - x2; dy1 = y3 - y2
s = (y0-y2)*dx1 - (x0-x2)*dy1
sm = dx0*dy1 - dy0*dx1
if -EPS < sm < EPS:
return None
return x0 + s*dx0/sm, y0 + s*dy0/sm
EPS = 1e-9
def convex_cut(P, line):
q0, q1 = line
N = len(P)
Q = []
for i in range(N):
p0 = P[i-1]; p1 = P[i]
cv0 = cross3(q0, q1, p0)
cv1 = cross3(q0, q1, p1)
if cv0 * cv1 < EPS:
v = cross_point(q0, q1, p0, p1)
if v is not None:
Q.append(v)
if cv1 > -EPS:
Q.append(p1)
return Q
def polygon_area(P):
s = 0
N = len(P)
for i in range(N):
p0 = P[i-1]; p1 = P[i]
s += p0[0]*p1[1] - p0[1]*p1[0]
return abs(s) / 2
def solve():
N, M = map(int, input().split())
if N == M == 0:
return False
P = [list(map(int, readline().split())) for i in range(N)]
Q = [list(map(int, readline().split())) for i in range(M)]
for i in range(M):
x0, y0 = Q[i]
P0 = P
for j in range(M):
if i == j:
continue
x1, y1 = Q[j]
ax = (x0 + x1) / 2; ay = (y0 + y1) / 2
q0 = (ax, ay)
q1 = (ax - (y1 - y0), ay + (x1 - x0))
P0 = convex_cut(P0, (q0, q1))
write("%.16f\n" % polygon_area(P0))
return True
while solve():
...
```
| 7,474 |
Provide a correct Python 3 solution for this coding contest problem.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
"Correct Solution:
```
N = int(input())
A = [0] * 101010
for i in range(N):
a, b = map(int, input().split())
A[a] += 1
A[b+1] -= 1
ans = 1
cuma = A[0]
for i, a in enumerate(A[1:], 1):
cuma += a
if cuma >= i-1:
ans = i
print(ans-1)
```
| 7,475 |
Provide a correct Python 3 solution for this coding contest problem.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
"Correct Solution:
```
import itertools
n=int(input())
table=[0 for i in range(100003)]
table[0]=1
for i in range(n):
a,b=map(int,input().split())
table[a]+=1
table[b+1]-=1
table=list(itertools.accumulate(table))
for i in range(len(table)):
if table[i]>=i:
ans=i
print(ans-1)
```
| 7,476 |
Provide a correct Python 3 solution for this coding contest problem.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
"Correct Solution:
```
n=int(input())
l=[0 for i in range(100003)]
for i in range(n):
a,b=map(int,input().split())
l[a]+=1
l[b+1]-=1
su=1
res=1
for i in range(100003):
su+=l[i]
if su>=i:
res=max(i,res)
print(res-1)
```
| 7,477 |
Provide a correct Python 3 solution for this coding contest problem.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
"Correct Solution:
```
from itertools import accumulate
n = int(input())
lst = [0] * 100002
for _ in range(n):
a, b = map(int, input().split())
lst[a - 1] += 1
lst[b] -= 1
lst = list(accumulate(lst))
for i in range(n, -1, -1):
if i <= lst[i]:
print(i)
break
```
| 7,478 |
Provide a correct Python 3 solution for this coding contest problem.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
"Correct Solution:
```
def main():
N = int(input())
ab = [list(map(int, input().split())) for i in range(N)]
imos = [0]*(N+3)
for a, b in ab:
imos[min(a,N+2)] += 1
imos[min(b+1,N+2)] -= 1
for i in range(N+1):
imos[i+1] += imos[i]
#print(imos)
ans = 0
for i, imo in enumerate(imos):
if (imo+1 >= i):
ans = i-1
print(ans)
main()
```
| 7,479 |
Provide a correct Python 3 solution for this coding contest problem.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
"Correct Solution:
```
N = int(input())
a=[]
p = 0
for i in range(N):
q=[int(j) for j in input().split()]
a.append([q[0]-1,q[1]])
p = max(p, q[1])
table=[0]*(p+1)
for i in range(len(a)):
table[a[i][0]]+=1
table[a[i][1]]-=1
for i in range(1,p+1):
table[i]+=table[i-1]
ans=0
for i, val in enumerate(table):
if val >= i and i <= N:
ans = max(i, ans)
print(ans)
```
| 7,480 |
Provide a correct Python 3 solution for this coding contest problem.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
"Correct Solution:
```
N = int(input())
MAX_N = int(1e5) + 2
acc = [0] * (MAX_N + 1)
acc[0] += 1
acc[MAX_N] -= 1
for _ in range(N):
a, b = map(int, input().split())
acc[a] += 1
acc[b + 1] -= 1
for i in range(MAX_N):
acc[i + 1] += acc[i]
for i in reversed(range(MAX_N)):
if acc[i] >= i:
print(i - 1)
break
```
| 7,481 |
Provide a correct Python 3 solution for this coding contest problem.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
"Correct Solution:
```
n = int(input())
a = [0] * (10**5 + 2)
for i in range(n) :
mi, ma = map(int, input().split())
a[mi-1] += 1
a[ma] -= 1
for i in range(n) :
a[i+1] += a[i]
ans = 0
for i in range(n, 0, -1) :
if a[i] >= i :
ans = i
break
print(ans)
```
| 7,482 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
Submitted Solution:
```
N = int(input())
MAXP = 100010
imos = [0 for i in range(MAXP)]
for i in range(N):
a,b = map(int,input().split())
imos[a-1] += 1
imos[b] -= 1
nums = [0]
for im in imos:
nums.append(nums[-1] + im)
for i,p in enumerate(reversed(nums)):
n = MAXP - 1 - i
if n == 0: break
if p >= n:
print(n)
exit()
print(0)
```
Yes
| 7,483 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
Submitted Solution:
```
N = int(input())
R = [0 for i in range(100003)]
for i in range(N):
a, b = map(int, input().split())
R[a] += 1
R[b+1] -= 1
x = 1
y = 1
for i in range(100003):
x += R[i]
if x >= i:
y = max(i, y)
print(y-1)
```
Yes
| 7,484 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
Submitted Solution:
```
#!/usr/bin/env python3
n = int(input())
li = [0] * (10**5 + 3)
for _ in range(n):
a, b = map(int, input().split())
li[a] += 1
li[b + 1] -= 1
for i in range(n + 1):
li[i + 1] += li[i]
ans = 0
for i in range(1, n + 2):
if i - 1 <= li[i]:
ans = max(ans, i - 1)
print(ans)
```
Yes
| 7,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
Submitted Solution:
```
#!/usr/bin/env python3
n = int(input())
# imos[k]: わたしがちょうどk人誘うときに来れる最大人数
imos = [0] * (10**5 + 2)
for _ in range(n):
a, b = map(int, input().split())
imos[a - 1] += 1
imos[b] -= 1
for i in range(n):
imos[i + 1] += imos[i]
ans = 0
for i in range(n + 1):
if imos[i] >= i:
ans = max(ans, i)
print(ans)
```
Yes
| 7,486 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
Submitted Solution:
```
N = int(input())
t = [0 for i in range(100002)]
for i in range(N):
a,b = [int(i) for i in input().split(' ')]
t[a-1] +=1
t[b] -= 1
ans = 0
for i in range(1,100001):
t[i] += t[i-1]
if (t[i] > i):
ans = i
print(ans)
```
No
| 7,487 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
Submitted Solution:
```
N=int(input())
friendlist=[0 for i in range(N+2)]
for i in range(N):
a,b=[int(j) for j in input().split(" ")]
for k in range(a,min(b+1,N+2)):
friendlist[k]+=1
#ab=[[int(i) for i in input().split(" ")] for j in range(N)]
#print(ab)
k=N+1
i=0
while k>=0:
if friendlist[k]>=k-1:
i=k-1
break
k-=1
print(i)
```
No
| 7,488 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
Submitted Solution:
```
N=int(input())
friendlist=[0 for i in range(N+1)]
for i in range(N):
a,b=[int(j) for j in input().split(" ")]
for k in range(a,min(N+1,b+1)):
friendlist[k]+=1
k=N
i=0
while k>=0:
if friendlist[k]>=k-1:
i=k-1
break
k-=1
print(i)
```
No
| 7,489 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
From tomorrow, the long-awaited summer vacation will begin. So I decided to invite my friends to go out to the sea.
However, many of my friends are shy. They would hate it if they knew that too many people would come with them.
Besides, many of my friends want to stand out. They will probably hate it if they know that not many people come with them.
Also, some of my friends are always shy, though they always want to stand out. They will surely hate if too many or too few people come with them.
This kind of thing should be more fun to do in large numbers. That's why I want to invite as many friends as possible. However, it is not good to force a friend you dislike.
How many friends can I invite up to?
I'm not very good at this kind of problem that seems to use my head. So I have a request for you. If you don't mind, could you solve this problem for me? No, I'm not overdoing it. But if I'm slacking off, I'm very happy.
Input
N
a1 b1
a2 b2
..
..
..
aN bN
The integer N (1 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of friends.
On the following N lines, the integer ai and the integer bi (2 ≤ ai ≤ bi ≤ 100,001) are written separated by blanks. The integers ai and bi written on the 1 + i line indicate that the i-th friend does not want to go to the sea unless the number of people going to the sea is ai or more and bi or less. Note that the number of people going to the sea includes "I".
Output
Output the maximum number of friends you can invite to the sea so that no friends dislike it.
Examples
Input
4
2 5
4 7
2 4
3 6
Output
3
Input
5
8 100001
7 100001
12 100001
8 100001
3 100001
Output
0
Input
6
2 9
4 8
6 7
6 6
5 7
2 100001
Output
5
Submitted Solution:
```
N = int(input())
P = []
for i in range(N):
a, b = map(int, input().split())
P.append((a, b))
Fmaxim = 0
for i in range(N+1):
Pcount = 1
for a, b in P:
if a <= i+1 <= b:
Pcount += 1
if Pcount >= i+1:
Fmaxim = max(Fmaxim, i)
print(Fmaxim)
```
No
| 7,490 |
Provide a correct Python 3 solution for this coding contest problem.
In the spring of 2014, a student successfully passed the university and started living alone. The problem here is what to do with the supper. He decided to plan a supper for the next N days.
He wants to maximize the total happiness he gets in N days. Of course, the more delicious or favorite you eat, the higher your happiness.
His dinner options are two, either head to a nearby dining room or cook for himself.
The happiness you get in the cafeteria depends on the menu of the day. The menu changes daily, but there is only one type every day, and all the menus for N days have already been released. So he knows all the information that if you go to the cafeteria on day i (1 ≤ i ≤ N) you will get the happiness of Ci.
The happiness obtained by self-catering is the self-catering power at the start of self-catering multiplied by a constant P. The initial value of self-catering power is Q, which is -1 if you go to the restaurant every day, +1 if you cook yourself, and fluctuates at the end of the meal of the day.
Find the maximum sum of happiness for him.
Constraints
* 1 ≤ N ≤ 500,000
* 0 ≤ P ≤ 500,000
* | Q | ≤ 500,000
* | Ci | ≤ 500,000
Input
The input is given in the following format as N + 1 line.
N P Q
C1
C2
::
CN
* The first line is given three integers N, P, and Q, which are the number of days, the constant for calculating the happiness of self-catering, and the initial value of self-catering power.
* From the 2nd line to the N + 1st line, one integer is given, and the i + 1st line gives the happiness obtained when going to the cafeteria on the i day.
Output
Output the maximum value of happiness that can be taken in one line.
Examples
Input
1 1 1
2
Output
2
Input
3 2 1
3
3
3
Output
12
Input
3 1 -1
2
-3
2
Output
2
Input
3 1 -10
-10
-10
-10
Output
-27
"Correct Solution:
```
n,p,q = map(int,input().split())
cn=[]
for i in range(n):
cn.append(int(input()))
difs=[p*(q-i)-cn[i] for i in range(n)]
difs=sorted(difs, reverse=True)
ans=[sum(cn)]
for i in range(n):
ans.append(ans[-1]+2*i*p+difs[i])
print(max(ans))
```
| 7,491 |
Provide a correct Python 3 solution for this coding contest problem.
In the spring of 2014, a student successfully passed the university and started living alone. The problem here is what to do with the supper. He decided to plan a supper for the next N days.
He wants to maximize the total happiness he gets in N days. Of course, the more delicious or favorite you eat, the higher your happiness.
His dinner options are two, either head to a nearby dining room or cook for himself.
The happiness you get in the cafeteria depends on the menu of the day. The menu changes daily, but there is only one type every day, and all the menus for N days have already been released. So he knows all the information that if you go to the cafeteria on day i (1 ≤ i ≤ N) you will get the happiness of Ci.
The happiness obtained by self-catering is the self-catering power at the start of self-catering multiplied by a constant P. The initial value of self-catering power is Q, which is -1 if you go to the restaurant every day, +1 if you cook yourself, and fluctuates at the end of the meal of the day.
Find the maximum sum of happiness for him.
Constraints
* 1 ≤ N ≤ 500,000
* 0 ≤ P ≤ 500,000
* | Q | ≤ 500,000
* | Ci | ≤ 500,000
Input
The input is given in the following format as N + 1 line.
N P Q
C1
C2
::
CN
* The first line is given three integers N, P, and Q, which are the number of days, the constant for calculating the happiness of self-catering, and the initial value of self-catering power.
* From the 2nd line to the N + 1st line, one integer is given, and the i + 1st line gives the happiness obtained when going to the cafeteria on the i day.
Output
Output the maximum value of happiness that can be taken in one line.
Examples
Input
1 1 1
2
Output
2
Input
3 2 1
3
3
3
Output
12
Input
3 1 -1
2
-3
2
Output
2
Input
3 1 -10
-10
-10
-10
Output
-27
"Correct Solution:
```
import sys
def solve():
readline = sys.stdin.readline
write = sys.stdout.write
N, P, Q = map(int, readline().split())
*C, = [int(readline()) for i in range(N)]
A = [0]*N
su = sum(C)
for i in range(N):
A[i] = P*(Q-i) - C[i]
A.sort(reverse=1)
ans = su
for i in range(N):
su += A[i]
ans = max(ans, su + P*i*(i+1))
write("%d\n" % ans)
solve()
```
| 7,492 |
Provide a correct Python 3 solution for this coding contest problem.
In the spring of 2014, a student successfully passed the university and started living alone. The problem here is what to do with the supper. He decided to plan a supper for the next N days.
He wants to maximize the total happiness he gets in N days. Of course, the more delicious or favorite you eat, the higher your happiness.
His dinner options are two, either head to a nearby dining room or cook for himself.
The happiness you get in the cafeteria depends on the menu of the day. The menu changes daily, but there is only one type every day, and all the menus for N days have already been released. So he knows all the information that if you go to the cafeteria on day i (1 ≤ i ≤ N) you will get the happiness of Ci.
The happiness obtained by self-catering is the self-catering power at the start of self-catering multiplied by a constant P. The initial value of self-catering power is Q, which is -1 if you go to the restaurant every day, +1 if you cook yourself, and fluctuates at the end of the meal of the day.
Find the maximum sum of happiness for him.
Constraints
* 1 ≤ N ≤ 500,000
* 0 ≤ P ≤ 500,000
* | Q | ≤ 500,000
* | Ci | ≤ 500,000
Input
The input is given in the following format as N + 1 line.
N P Q
C1
C2
::
CN
* The first line is given three integers N, P, and Q, which are the number of days, the constant for calculating the happiness of self-catering, and the initial value of self-catering power.
* From the 2nd line to the N + 1st line, one integer is given, and the i + 1st line gives the happiness obtained when going to the cafeteria on the i day.
Output
Output the maximum value of happiness that can be taken in one line.
Examples
Input
1 1 1
2
Output
2
Input
3 2 1
3
3
3
Output
12
Input
3 1 -1
2
-3
2
Output
2
Input
3 1 -10
-10
-10
-10
Output
-27
"Correct Solution:
```
n,p,q = map(int, input().split())
cn = []
for i in range(n):
cn.append(int(input()))
difs = [p*(q-i) - cn[i] for i in range(n)] ##0번째 자취에서 1번 i번째날 자취할 때의 증가분
difs = sorted(difs, reverse = True) ##제일 증가분이 큰 순서대로 sort
ans = [sum(cn)] ##(ans[i] = i번 자취시 행복도의 최대값) 으로 만들것임
for i in range(n):
ans.append(ans[-1] + 2*i*p + difs[i])
##i=0에서는 자취를 한번만 한 것으로 자취파워가 올라간 것을 반영한 2ip는 0이 된다.
##(자취파워 올라간게 반영되지 않으므로)
print(max(ans)) ##0~n번 자취할때 의 최대값들중 최대값을 출력.
```
| 7,493 |
Provide a correct Python 3 solution for this coding contest problem.
In the spring of 2014, a student successfully passed the university and started living alone. The problem here is what to do with the supper. He decided to plan a supper for the next N days.
He wants to maximize the total happiness he gets in N days. Of course, the more delicious or favorite you eat, the higher your happiness.
His dinner options are two, either head to a nearby dining room or cook for himself.
The happiness you get in the cafeteria depends on the menu of the day. The menu changes daily, but there is only one type every day, and all the menus for N days have already been released. So he knows all the information that if you go to the cafeteria on day i (1 ≤ i ≤ N) you will get the happiness of Ci.
The happiness obtained by self-catering is the self-catering power at the start of self-catering multiplied by a constant P. The initial value of self-catering power is Q, which is -1 if you go to the restaurant every day, +1 if you cook yourself, and fluctuates at the end of the meal of the day.
Find the maximum sum of happiness for him.
Constraints
* 1 ≤ N ≤ 500,000
* 0 ≤ P ≤ 500,000
* | Q | ≤ 500,000
* | Ci | ≤ 500,000
Input
The input is given in the following format as N + 1 line.
N P Q
C1
C2
::
CN
* The first line is given three integers N, P, and Q, which are the number of days, the constant for calculating the happiness of self-catering, and the initial value of self-catering power.
* From the 2nd line to the N + 1st line, one integer is given, and the i + 1st line gives the happiness obtained when going to the cafeteria on the i day.
Output
Output the maximum value of happiness that can be taken in one line.
Examples
Input
1 1 1
2
Output
2
Input
3 2 1
3
3
3
Output
12
Input
3 1 -1
2
-3
2
Output
2
Input
3 1 -10
-10
-10
-10
Output
-27
"Correct Solution:
```
INF = 10 ** 15
MOD = 10 ** 9 + 7
def main():
N,P,Q = map(int,input().split())
C = [int(input()) for _ in range(N)]
ret = sum(C)
C = [c + P*i for i,c in enumerate(C)]
C.sort()
x = 0
ans = ret
for i in range(N):
ret += -C[i] + P*(2*x + Q)
ans = max(ans,ret)
x += 1
print(ans)
if __name__ == '__main__':
main()
```
| 7,494 |
Provide a correct Python 3 solution for this coding contest problem.
In the spring of 2014, a student successfully passed the university and started living alone. The problem here is what to do with the supper. He decided to plan a supper for the next N days.
He wants to maximize the total happiness he gets in N days. Of course, the more delicious or favorite you eat, the higher your happiness.
His dinner options are two, either head to a nearby dining room or cook for himself.
The happiness you get in the cafeteria depends on the menu of the day. The menu changes daily, but there is only one type every day, and all the menus for N days have already been released. So he knows all the information that if you go to the cafeteria on day i (1 ≤ i ≤ N) you will get the happiness of Ci.
The happiness obtained by self-catering is the self-catering power at the start of self-catering multiplied by a constant P. The initial value of self-catering power is Q, which is -1 if you go to the restaurant every day, +1 if you cook yourself, and fluctuates at the end of the meal of the day.
Find the maximum sum of happiness for him.
Constraints
* 1 ≤ N ≤ 500,000
* 0 ≤ P ≤ 500,000
* | Q | ≤ 500,000
* | Ci | ≤ 500,000
Input
The input is given in the following format as N + 1 line.
N P Q
C1
C2
::
CN
* The first line is given three integers N, P, and Q, which are the number of days, the constant for calculating the happiness of self-catering, and the initial value of self-catering power.
* From the 2nd line to the N + 1st line, one integer is given, and the i + 1st line gives the happiness obtained when going to the cafeteria on the i day.
Output
Output the maximum value of happiness that can be taken in one line.
Examples
Input
1 1 1
2
Output
2
Input
3 2 1
3
3
3
Output
12
Input
3 1 -1
2
-3
2
Output
2
Input
3 1 -10
-10
-10
-10
Output
-27
"Correct Solution:
```
#着席位置は中央*奥
#問題は「Dinner」(http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2642&lang=jp)
#方針としては、自炊をする回数(0~n)を決め打ちし、それぞれの時の最大値を計算してその最大値を返すことにする
#n回自炊するとき、自炊パワーはn-1回自壊する時に比べ最終的に2増える。
#これを考えると、n回自炊する時、高まる自炊パワーによる幸福度の増加分はn*(n+1)となる
#したがって、まずリストdifsに「自炊と食堂の幸福度の差分」を全て入れる
#これを降順にソートし、n回自炊した時の幸福度の最大値をansに入れていく
#ansの最大値を出力して、終了
n,p,q = map(int,input().split())
cs = []
for i in range(n):
cs.append(int(input()))
ans = [sum(cs)]
difs = [p * (q-i) - cs[i] for i in range(n)]
difs.sort(reverse = True)
for i in range(n):
ans.append(ans[-1] + 2 * i * p + difs[i])
print(max(ans))
```
| 7,495 |
Provide a correct Python 3 solution for this coding contest problem.
In the spring of 2014, a student successfully passed the university and started living alone. The problem here is what to do with the supper. He decided to plan a supper for the next N days.
He wants to maximize the total happiness he gets in N days. Of course, the more delicious or favorite you eat, the higher your happiness.
His dinner options are two, either head to a nearby dining room or cook for himself.
The happiness you get in the cafeteria depends on the menu of the day. The menu changes daily, but there is only one type every day, and all the menus for N days have already been released. So he knows all the information that if you go to the cafeteria on day i (1 ≤ i ≤ N) you will get the happiness of Ci.
The happiness obtained by self-catering is the self-catering power at the start of self-catering multiplied by a constant P. The initial value of self-catering power is Q, which is -1 if you go to the restaurant every day, +1 if you cook yourself, and fluctuates at the end of the meal of the day.
Find the maximum sum of happiness for him.
Constraints
* 1 ≤ N ≤ 500,000
* 0 ≤ P ≤ 500,000
* | Q | ≤ 500,000
* | Ci | ≤ 500,000
Input
The input is given in the following format as N + 1 line.
N P Q
C1
C2
::
CN
* The first line is given three integers N, P, and Q, which are the number of days, the constant for calculating the happiness of self-catering, and the initial value of self-catering power.
* From the 2nd line to the N + 1st line, one integer is given, and the i + 1st line gives the happiness obtained when going to the cafeteria on the i day.
Output
Output the maximum value of happiness that can be taken in one line.
Examples
Input
1 1 1
2
Output
2
Input
3 2 1
3
3
3
Output
12
Input
3 1 -1
2
-3
2
Output
2
Input
3 1 -10
-10
-10
-10
Output
-27
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**3
eps = 1.0 / 10**10
mod = 10**9+7
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():
n, p, q = LI()
c = [I() for _ in range(n)]
s = sum(c)
a = sorted([[c[i]+p*i, i] for i in range(n)])
r = s
for i in range(n):
s -= c[a[i][1]] + p * a[i][1]
t = s + p*i*(i+1) + p*q*(i+1)
if t > r:
r = t
return r
print(main())
```
| 7,496 |
Provide a correct Python 3 solution for this coding contest problem.
In the spring of 2014, a student successfully passed the university and started living alone. The problem here is what to do with the supper. He decided to plan a supper for the next N days.
He wants to maximize the total happiness he gets in N days. Of course, the more delicious or favorite you eat, the higher your happiness.
His dinner options are two, either head to a nearby dining room or cook for himself.
The happiness you get in the cafeteria depends on the menu of the day. The menu changes daily, but there is only one type every day, and all the menus for N days have already been released. So he knows all the information that if you go to the cafeteria on day i (1 ≤ i ≤ N) you will get the happiness of Ci.
The happiness obtained by self-catering is the self-catering power at the start of self-catering multiplied by a constant P. The initial value of self-catering power is Q, which is -1 if you go to the restaurant every day, +1 if you cook yourself, and fluctuates at the end of the meal of the day.
Find the maximum sum of happiness for him.
Constraints
* 1 ≤ N ≤ 500,000
* 0 ≤ P ≤ 500,000
* | Q | ≤ 500,000
* | Ci | ≤ 500,000
Input
The input is given in the following format as N + 1 line.
N P Q
C1
C2
::
CN
* The first line is given three integers N, P, and Q, which are the number of days, the constant for calculating the happiness of self-catering, and the initial value of self-catering power.
* From the 2nd line to the N + 1st line, one integer is given, and the i + 1st line gives the happiness obtained when going to the cafeteria on the i day.
Output
Output the maximum value of happiness that can be taken in one line.
Examples
Input
1 1 1
2
Output
2
Input
3 2 1
3
3
3
Output
12
Input
3 1 -1
2
-3
2
Output
2
Input
3 1 -10
-10
-10
-10
Output
-27
"Correct Solution:
```
n,p,q=map(int,input().split())
b=[0]*n
for i in range(n):b[i]=p*i+int(input())
b.sort()
a=q*p*n+p*n*~-n//2;s=0
for i in range(1,-~n):
s+=b[n-i]
a=max(a,p*q*(n-i)+p*(n-i)*(~-n-i)//2-p*i*(i-1)//2-p*i*(n-i)+s)
print(a)
```
| 7,497 |
Provide a correct Python 3 solution for this coding contest problem.
In the spring of 2014, a student successfully passed the university and started living alone. The problem here is what to do with the supper. He decided to plan a supper for the next N days.
He wants to maximize the total happiness he gets in N days. Of course, the more delicious or favorite you eat, the higher your happiness.
His dinner options are two, either head to a nearby dining room or cook for himself.
The happiness you get in the cafeteria depends on the menu of the day. The menu changes daily, but there is only one type every day, and all the menus for N days have already been released. So he knows all the information that if you go to the cafeteria on day i (1 ≤ i ≤ N) you will get the happiness of Ci.
The happiness obtained by self-catering is the self-catering power at the start of self-catering multiplied by a constant P. The initial value of self-catering power is Q, which is -1 if you go to the restaurant every day, +1 if you cook yourself, and fluctuates at the end of the meal of the day.
Find the maximum sum of happiness for him.
Constraints
* 1 ≤ N ≤ 500,000
* 0 ≤ P ≤ 500,000
* | Q | ≤ 500,000
* | Ci | ≤ 500,000
Input
The input is given in the following format as N + 1 line.
N P Q
C1
C2
::
CN
* The first line is given three integers N, P, and Q, which are the number of days, the constant for calculating the happiness of self-catering, and the initial value of self-catering power.
* From the 2nd line to the N + 1st line, one integer is given, and the i + 1st line gives the happiness obtained when going to the cafeteria on the i day.
Output
Output the maximum value of happiness that can be taken in one line.
Examples
Input
1 1 1
2
Output
2
Input
3 2 1
3
3
3
Output
12
Input
3 1 -1
2
-3
2
Output
2
Input
3 1 -10
-10
-10
-10
Output
-27
"Correct Solution:
```
#演習2-18
def solve(N,P,Q,menu):
all_happy = [P*(Q-i) - menu[i] for i in range(N)]
all_happy = sorted(all_happy, reverse = True)
happy = [sum(menu)]
for i in range(N):
happy.append(happy[-1] + P*i*2 + all_happy[i])
return(max(happy))
while True:
try:
N,P,Q = map(int,input().split())
menu = []
for i in range(N):
menu.append(int(input()))
print(solve(N,P,Q,menu))
except:
break
```
| 7,498 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In the spring of 2014, a student successfully passed the university and started living alone. The problem here is what to do with the supper. He decided to plan a supper for the next N days.
He wants to maximize the total happiness he gets in N days. Of course, the more delicious or favorite you eat, the higher your happiness.
His dinner options are two, either head to a nearby dining room or cook for himself.
The happiness you get in the cafeteria depends on the menu of the day. The menu changes daily, but there is only one type every day, and all the menus for N days have already been released. So he knows all the information that if you go to the cafeteria on day i (1 ≤ i ≤ N) you will get the happiness of Ci.
The happiness obtained by self-catering is the self-catering power at the start of self-catering multiplied by a constant P. The initial value of self-catering power is Q, which is -1 if you go to the restaurant every day, +1 if you cook yourself, and fluctuates at the end of the meal of the day.
Find the maximum sum of happiness for him.
Constraints
* 1 ≤ N ≤ 500,000
* 0 ≤ P ≤ 500,000
* | Q | ≤ 500,000
* | Ci | ≤ 500,000
Input
The input is given in the following format as N + 1 line.
N P Q
C1
C2
::
CN
* The first line is given three integers N, P, and Q, which are the number of days, the constant for calculating the happiness of self-catering, and the initial value of self-catering power.
* From the 2nd line to the N + 1st line, one integer is given, and the i + 1st line gives the happiness obtained when going to the cafeteria on the i day.
Output
Output the maximum value of happiness that can be taken in one line.
Examples
Input
1 1 1
2
Output
2
Input
3 2 1
3
3
3
Output
12
Input
3 1 -1
2
-3
2
Output
2
Input
3 1 -10
-10
-10
-10
Output
-27
Submitted Solution:
```
tmp = list(map(int,input().split()))
n,p,q = tmp[0],tmp[1],tmp[2]
cs = []
for i in range(n):
cs.append(int(input()))
ans = [sum(cs)]
difs = [p * (q-i) - cs[i] for i in range(n)]
difs.sort(reverse = True)
for i in range(n):
ans.append(ans[-1] + 2 * i * p + difs[i])
print(max(ans))
```
Yes
| 7,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.