message
stringlengths
2
19.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
322
108k
cluster
float64
15
15
__index_level_0__
int64
644
217k
Provide a correct Python 3 solution for this coding contest problem. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF
instruction
0
105,043
15
210,086
"Correct Solution: ``` I=lambda:map(int,input().split());F=1e21;r=range;n,m=I();f=[-F,F];X=[0]+f;Y=X[:];R=[(f,F),(f,-F)];H=[(F,f),(-F,f)] for i in r(n):*a,c=I();R+=[(a,c)];Y+=[c];X+=a for i in r(m):a,*b=I();H+=[(a,b)];X+=[a];Y+=b def g(X):s=dict(enumerate(sorted(set(X))));return{s[i]:i for i in s},s,len(s)+1 h,s,K=g(X);w,t,L=g(Y);j=lambda:[[0]*(K+1)for i in r(L+1)];V=j();U=j();v=j() for(a,b),c in R:U[w[c]][h[a]]+=1;U[w[c]][h[b]]+=-1 for d,(e,f)in H:V[w[e]][h[d]]+=1;V[w[f]][h[d]]+=-1 for i in r(L): for j in r(K):U[i][j+1]+=U[i][j];V[i+1][j]+=V[i][j] q=[(h[0],w[0])];v[w[0]][h[0]]=1;a=0 while q: x,y=q.pop();a+=(s[x]-s[x+1])*(t[y]-t[y+1]) for e,f in[(-1,0),(1,0),(0,1),(0,-1)]: c=x+e;d=y+f if(K>c>=0<=d<L)*v[d][c]==0: if U[(f>0)+y][x]|e==0 or V[y][(e>0)+x]|f==0:q+=[(c,d)];v[d][c]=1 if a>F:a='INF' print(a) ```
output
1
105,043
15
210,087
Provide a correct Python 3 solution for this coding contest problem. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF
instruction
0
105,044
15
210,088
"Correct Solution: ``` I=lambda:map(int,input().split());F=1e21;r=range;n,m=I();f=[-F,F];X=set([0]+f);Y=set(X);R=[(f,F),(f,-F)];H=[(F,f),(-F,f)] for i in r(n):a,b,c=I();R+=[((a,b),c)];Y.add(c);X.add(a);X.add(b) for i in r(m):a,b,c=I();H+=[(a,(b,c))];X.add(a);Y.add(b);Y.add(c) s=dict(enumerate(sorted(X)));K=len(s);t=dict(enumerate(sorted(Y)));L=len(t);h=dict(zip(s.values(),s.keys()));w=dict(zip(t.values(),t.keys()));V=[[0]*-~K for i in r(L+1)];U=[i[:]for i in V];v=[i[:]for i in V] for(a,b),c in R:U[w[c]][h[a]]+=1;U[w[c]][h[b]]+=-1 for i in r(L): for j in r(K):U[i][j+1]+=U[i][j] for d,(e,f)in H:V[w[e]][h[d]]+=1;V[w[f]][h[d]]+=-1 for j in r(K): for i in r(L):V[i+1][j]+=V[i][j] q=[(h[0],w[0])];v[w[0]][h[0]]=1;a=0 while q: x,y=q.pop();a+=(s[x]-s[x+1])*(t[y]-t[y+1]) for e,f in[(-1,0),(1,0),(0,1),(0,-1)]: c=x+e;d=y+f if(K>c>=0<=d<L)*v[d][c]==0: if U[(f>0)+y][x]|e==0 or V[y][(e>0)+x]|f==0:q+=[(c,d)];v[d][c]=1 if a>F:a='INF' print(a) ```
output
1
105,044
15
210,089
Provide a correct Python 3 solution for this coding contest problem. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF
instruction
0
105,045
15
210,090
"Correct Solution: ``` def main(): import sys sys.setrecursionlimit(10**9) input = sys.stdin.readline from bisect import bisect_left, bisect_right INF = 10**18 n, m = map(int, input().split()) a = [list(map(int, input().split())) for i in range(n)] b = [list(map(int, input().split())) for i in range(m)] X = {-INF, INF} Y = {-INF, INF} for i in a: Y.add(i[2]) for i in b: X.add(i[0]) X = list(sorted(X)) Y = list(sorted(Y)) n = len(X) - 1 m = len(Y) - 1 wallx = [[False] * m for i in range(n)] wally = [[False] * m for i in range(n)] for x1, x2, y1 in a: x1 = bisect_left(X, x1) y1 = bisect_left(Y, y1) x2 = bisect_right(X, x2) - 1 for i in range(x1, x2): wally[i][y1] = True for x1, y1, y2 in b: x1 = bisect_left(X, x1) y1 = bisect_left(Y, y1) y2 = bisect_right(Y, y2) - 1 for i in range(y1, y2): wallx[x1][i] = True cow = [[False] * m for i in range(n)] cx = bisect_right(X, 0) - 1 cy = bisect_right(Y, 0) - 1 cow[cx][cy] = True q = [(cx, cy)] ans = 0 while q: x, y = q.pop() if not x or not y: print("INF") sys.exit() ans += (X[x + 1] - X[x]) * (Y[y + 1] - Y[y]) if x and not wallx[x][y] and not cow[x - 1][y]: cow[x - 1][y] = True q.append((x - 1, y)) if y and not wally[x][y] and not cow[x][y - 1]: cow[x][y - 1] = True q.append((x, y - 1)) if x + 1 < n and not wallx[x + 1][y] and not cow[x + 1][y]: cow[x + 1][y] = True q.append((x + 1, y)) if y + 1 < m and not wally[x][y + 1] and not cow[x][y + 1]: cow[x][y + 1] = True q.append((x, y + 1)) print(ans) main() ```
output
1
105,045
15
210,091
Provide a correct Python 3 solution for this coding contest problem. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF
instruction
0
105,046
15
210,092
"Correct Solution: ``` from collections import deque def LI():return [int(i) for i in input().split()] ans=0 inf=1<<65 n,m=LI() X=[0,inf,-inf] Y=[0,inf,-inf] V=[] H=[] for i in range(n): a,b,c=LI() V.append(((a,b),c)) Y.append(c) X.append(a) X.append(b) n+=2 V.append(((-inf,inf),inf)) V.append(((-inf,inf),-inf)) for i in range(m): a,b,c=LI() H.append((a,(b,c))) X.append(a) Y.append(b) Y.append(c) m+=2 H.append((inf,(-inf,inf))) H.append((-inf,(-inf,inf))) X.sort() xdc={} c=1 for j in sorted(set(X)): xdc[c]=j c+=1 nx=c-1 Y.sort() ydc={} c=1 for j in sorted(set(Y)): ydc[c]=j c+=1 ny=c-1 xdcr=dict(zip(xdc.values(),xdc.keys())) ydcr=dict(zip(ydc.values(),ydc.keys())) mpy=[[0]*(nx+1+1) for i in range(ny+1+1)] mpx=[i[:]for i in mpy] for (a,b),c in V: mpx[ydcr[c]][xdcr[a]]+=1 mpx[ydcr[c]][xdcr[b]]+=-1 for i in range(ny+1): for j in range(nx): mpx[i][j+1]+=mpx[i][j] for d,(e,f) in H: mpy[ydcr[e]][xdcr[d]]+=1 mpy[ydcr[f]][xdcr[d]]+=-1 for j in range(nx+1): for i in range(ny): mpy[i+1][j]+=mpy[i][j] v=[[0]*(nx+1) for i in range(ny+1)] q=[(xdcr[0],ydcr[0])] v[ydcr[0]][xdcr[0]]=1 while q: cx,cy=q.pop() ans+=(xdc[cx]-xdc[cx+1])*(ydc[cy]-ydc[cy+1]) for dx,dy in [(-1,0),(1,0),(0,1),(0,-1)]: nbx=cx+dx nby=cy+dy if (0>nbx>=nx)or(0>nby>=ny)or v[nby][nbx]==1: continue if dy!=0: if mpx[-~dy//2+cy][cx]==0: q.append((nbx,nby)) v[nby][nbx]=1 else: if mpy[cy][-~dx//2+cx]==0: q.append((nbx,nby)) v[nby][nbx]=1 if ans>=inf: ans='INF' print(ans) ```
output
1
105,046
15
210,093
Provide a correct Python 3 solution for this coding contest problem. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF
instruction
0
105,047
15
210,094
"Correct Solution: ``` import sys from typing import Iterable, Tuple, Union class nd (object): getter = ( lambda a, i: a, lambda a, i: a[i[0]], lambda a, i: a[i[0]][i[1]], lambda a, i: a[i[0]][i[1]][i[2]], lambda a, i: a[i[0]][i[1]][i[2]][i[3]], lambda a, i: a[i[0]][i[1]][i[2]][i[3]][i[4]], lambda a, i: a[i[0]][i[1]][i[2]][i[3]][i[4]][i[5]], ) class _setter (object): def __getitem__(self, n : int): setter_getter = nd.getter[n-1] def setter(a, i, v): setter_getter(a, i[:-1])[i[-1]] = v return setter setter = _setter() initializer = ( lambda s, v: [v] * s, lambda s, v: [v] * s[0], lambda s, v: [[v] * s[1] for _ in range(s[0])], lambda s, v: [[[v] * s[2] for _ in range(s[1])] for _ in range(s[0])], lambda s, v: [[[[v] * s[3] for _ in range(s[2])] for _ in range(s[1])] for _ in range(s[0])], lambda s, v: [[[[[v] * s[4] for _ in range(s[3])] for _ in range(s[2])] for _ in range(s[1])] for _ in range(s[0])], lambda s, v: [[[[[[v] * s[5] for _ in range(s[4])] for _ in range(s[3])] for _ in range(s[2])] for _ in range(s[1])] for _ in range(s[0])], ) shape_getter = ( lambda a: len(a), lambda a: (len(a),), lambda a: (len(a), len(a[0])), lambda a: (len(a), len(a[0]), len(a[0][0])), lambda a: (len(a), len(a[0]), len(a[0][0]), len(a[0][0][0])), lambda a: (len(a), len(a[0]), len(a[0][0]), len(a[0][0][0]), len(a[0][0][0][0])), lambda a: (len(a), len(a[0]), len(a[0][0]), len(a[0][0][0]), len(a[0][0][0][0]), len(a[0][0][0][0][0])), ) indices_iterator = ( lambda s: iter(range(s)), lambda s: ((i,) for i in range(s[0])), lambda s: ((i, j) for j in range(s[1]) for i in range(s[0])), lambda s: ((i, j, k) for k in range(s[2]) for j in range(s[1]) for i in range(s[0])), lambda s: ((i, j, k, l) for l in range(s[3]) for k in range(s[2]) for j in range(s[1]) for i in range(s[0])), lambda s: ((i, j, k, l, m) for m in range(s[4]) for l in range(s[3]) for k in range(s[2]) for j in range(s[1]) for i in range(s[0])), lambda s: ((i, j, k, l, m, n) for n in range(s[5]) for m in range(s[4]) for l in range(s[3]) for k in range(s[2]) for j in range(s[1]) for i in range(s[0])), ) iterable_product = ( lambda s: iter(s), lambda s: ((i,) for i in s[0]), lambda s: ((i, j) for j in s[1] for i in s[0]), lambda s: ((i, j, k) for k in s[2] for j in s[1] for i in s[0]), lambda s: ((i, j, k, l) for l in s[3] for k in s[2] for j in s[1] for i in s[0]), lambda s: ((i, j, k, l, m) for m in s[4] for l in s[3] for k in s[2] for j in s[1] for i in s[0]), lambda s: ((i, j, k, l, m, n) for n in s[5] for m in s[4] for l in s[3] for k in s[2] for j in s[1] for i in s[0]), ) @classmethod def full(cls, fill_value, shape : Union[int, Tuple[int], Iterable[int]]): if isinstance(shape, int): return cls.initializer[0](shape, fill_value) elif not isinstance(shape, tuple): shape = tuple(shape) return cls.initializer[len(shape)](shape, fill_value) @classmethod def fromiter(cls, iterable : Iterable, ndim=1): if ndim == 1: return list(iterable) else: return list(map(cls.fromiter, iterable)) @classmethod def nones(cls, shape : Union[int, Tuple[int], Iterable[int]]): return cls.full(None, shape) @classmethod def zeros(cls, shape : Union[int, Tuple[int], Iterable[int]], type=int): return cls.full(type(0), shape) @classmethod def ones(cls, shape : Union[int, Tuple[int], Iterable[int]], type=int): return cls.full(type(1), shape) class _range (object): def __getitem__(self, shape : Union[int, slice, Tuple[Union[int, slice]]]): if isinstance(shape, int): return iter(range(shape)) elif isinstance(shape, slice): return iter(range(shape.stop)[shape]) else: shape = tuple(range(s.stop)[s] for s in shape) return nd.iterable_product[len(shape)](shape) def __call__(self, shape : Union[int, slice, Tuple[Union[int, slice]]]): return self[shape] range = _range() def bytes_to_str(x : bytes): return x.decode('utf-8') def inputs(func=bytes_to_str, sep=None, maxsplit=-1): return map(func, sys.stdin.buffer.readline().split(sep=sep, maxsplit=maxsplit)) def inputs_1d(func=bytes_to_str, **kwargs): return nd(inputs(func, **kwargs)) def inputs_2d(nrows : int, func=bytes_to_str, **kwargs): return nd.fromiter( (inputs(func, **kwargs) for _ in range(nrows)), ndim=2 ) def inputs_2d_T(nrows : int, func=bytes_to_str, **kwargs): return nd.fromiter( zip(*(inputs(func, **kwargs) for _ in range(nrows))), ndim=2 ) from collections import deque from typing import Optional class BreadthFirstSearch (object): __slots__ = [ 'shape', 'pushed', '_deque', '_getter', '_setter' ] def __init__(self, shape : Union[int, Iterable[int]]): self.shape = (shape,) if isinstance(shape, int) else tuple(shape) self.pushed = nd.zeros(self.shape, type=bool) self._deque = deque() self._getter = nd.getter[len(self.shape)] self._setter = nd.setter[len(self.shape)] def push(self, position : Tuple[int]): if not self._getter(self.pushed, position): self._setter(self.pushed, position, True) self._deque.append(position) def peek(self) -> Optional[Tuple[int]]: return self._deque[0] if self._deque else None def pop(self) -> Optional[Tuple[int]]: return self._deque.popleft() if self._deque else None def __bool__(self): return bool(self._deque) from bisect import bisect_left, bisect_right N, M = inputs(int) A, B, C = inputs_2d_T(N, int) D, E, F = inputs_2d_T(M, int) xs = sorted(set(C)) ys = sorted(set(D)) x_guard = nd.zeros((len(xs)+1, len(ys)+1), type=bool) y_guard = nd.zeros((len(xs)+1, len(ys)+1), type=bool) for a, b, c in zip(A, B, C): c = bisect_right(xs, c) a = bisect_left(ys, a) + 1 b = bisect_right(ys, b) for y in range(a, b): x_guard[c][y] = True for d, e, f in zip(D, E, F): d = bisect_right(ys, d) e = bisect_left(xs, e) + 1 f = bisect_right(xs, f) for x in range(e, f): y_guard[x][d] = True cow = ( bisect_right(xs, 0), bisect_right(ys, 0) ) bfs = BreadthFirstSearch(shape=(len(xs)+1, len(ys)+1)) bfs.push(cow) area = 0 while bfs: xi, yi = bfs.pop() if 0 < xi < len(xs) and 0 < yi < len(ys): area += (xs[xi] - xs[xi-1]) * (ys[yi] - ys[yi-1]) if not x_guard[xi][yi]: bfs.push((xi-1, yi)) if not x_guard[xi+1][yi]: bfs.push((xi+1, yi)) if not y_guard[xi][yi]: bfs.push((xi, yi-1)) if not y_guard[xi][yi+1]: bfs.push((xi, yi+1)) else: area = 'INF' break print(area) ```
output
1
105,047
15
210,095
Provide a correct Python 3 solution for this coding contest problem. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF
instruction
0
105,048
15
210,096
"Correct Solution: ``` from collections import deque import bisect INF = float("inf") N,M = map(int,input().split()) xtic = {0,-INF,INF} ytic = {0,-INF,INF} hor = [] for _ in range(N): a,b,c = map(int,input().split()) hor.append((c,a,b)) xtic.add(a) xtic.add(b) ytic.add(c) ver = [] for _ in range(M): d,e,f = map(int,input().split()) ver.append((d,e,f)) xtic.add(d) ytic.add(e) ytic.add(f) xtic = list(xtic) ytic = list(ytic) xtic.sort() ytic.sort() xdic = {xtic[i]:i+1 for i in range(len(xtic))} ydic = {ytic[i]:i+1 for i in range(len(ytic))} gyaku_xdic = {xdic[k]:k for k in xdic} gyaku_ydic = {ydic[k]:k for k in ydic} hor.sort() ver.sort() hor_dic = {} ver_dic = {} now = None for c,a,b in hor: c,a,b = ydic[c],xdic[a],xdic[b] if c != now: hor_dic[c] = (1<<b) - (1<<a) else: hor_dic[c] |= (1<<b) - (1<<a) now = c now = None for d,e,f in ver: d,e,f = xdic[d],ydic[e],ydic[f] if d != now: ver_dic[d] = (1<<f) - (1<<e) else: ver_dic[d] |= (1<<f) - (1<<e) now = d def is_connected(x,y,dx,dy): if dx == 0: if dy > 0: if (hor_wall[y+1]>>x)&1: return False return True else: if (hor_wall[y]>>x)&1: return False return True else: if dx > 0: if (ver_wall[x+1]>>y)&1: return False return True else: if (ver_wall[x]>>y)&1: return False return True def calc_area(x,y): X = gyaku_xdic[x+1] - gyaku_xdic[x] Y = gyaku_ydic[y+1] - gyaku_ydic[y] return X*Y offset = [(1,0),(0,1),(-1,0),(0,-1)] x0 = bisect.bisect(xtic,0) y0 = bisect.bisect(ytic,0) W,H = len(xtic)+1 ,len(ytic)+1 hor_wall = [0 for i in range(H)] ver_wall = [0 for i in range(W)] for k in hor_dic: hor_wall[k] = hor_dic[k] for k in ver_dic: ver_wall[k] = ver_dic[k] d = [[0 for i in range(W)] for j in range(H)] d[y0][x0] = 1 q = deque([(x0,y0)]) area = 0 while q: x,y = q.pop() area += calc_area(x,y) for dx,dy in offset: nx,ny = x+dx,y+dy if 0<=nx<W and 0<=ny<H: if is_connected(x,y,dx,dy): if nx == 0 or ny == 0 or nx == W-1 or ny == H-1: print("INF") exit() if d[ny][nx] == 0: d[ny][nx] = 1 q.append((nx,ny)) print(area) ```
output
1
105,048
15
210,097
Provide a correct Python 3 solution for this coding contest problem. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF
instruction
0
105,049
15
210,098
"Correct Solution: ``` def f_single_dot(): # https://atcoder.jp/contests/abc168/submissions/13368489 import sys from collections import deque input = sys.stdin.readline N, M = [int(i) for i in input().split()] X, Y = set([0]), set([0]) vertical_lines = [] for _ in range(N): a, b, grid = map(int, input().split()) vertical_lines.append((a, b, grid)) X |= {a, b} Y |= {grid} horizontal_lines = [] for _ in range(M): d, e, f = map(int, input().split()) horizontal_lines.append((d, e, f)) X |= {d} Y |= {e, f} X = sorted(X) Y = sorted(Y) dictx, dicty = {n: i * 2 for i, n in enumerate(X)}, {n: i * 2 for i, n in enumerate(Y)} LX = [X[i // 2 + 1] - X[i // 2] if i % 2 else 0 for i in range(len(X) * 2 - 1)] LY = [Y[i // 2 + 1] - Y[i // 2] if i % 2 else 0 for i in range(len(Y) * 2 - 1)] grid = [[0] * (len(X) * 2 - 1) for _ in range(len(Y) * 2 - 1)] for a, b, c in vertical_lines: a, b, c = dictx[a], dictx[b], dicty[c] for x in range(a, b + 1): grid[c][x] = 1 for d, e, f in horizontal_lines: d, e, f = dictx[d], dicty[e], dicty[f] for y in range(e, f + 1): grid[y][d] = 1 que = deque() used = [[0] * len(X) * 2 for _ in range(len(Y) * 2)] dy = [1, 1, -1, -1] dx = [1, -1, 1, -1] for k in range(4): nny, nnx = dicty[0] + dy[k], dictx[0] + dx[k] if 1 <= nny < len(Y) * 2 - 1 and 1 <= nnx < len(X) * 2 - 1: que.append((nny, nnx)) used[nny][nnx] = 1 ans = 0 dy = [1, 0, -1, 0] dx = [0, 1, 0, -1] while que: y, x = que.popleft() if y % 2 and x % 2: ans += LY[y] * LX[x] for k in range(4): ny, nx = y + dy[k], x + dx[k] nny, nnx = ny + dy[k], nx + dx[k] if grid[ny][nx] == 0: if nny < 0 or nny >= len(Y) * 2 - 1 or nnx < 0 or nnx >= len(X) * 2 - 1: return 'INF' if not used[nny][nnx]: que.append((nny, nnx)) used[nny][nnx] = 1 return ans print(f_single_dot()) ```
output
1
105,049
15
210,099
Provide a correct Python 3 solution for this coding contest problem. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF
instruction
0
105,050
15
210,100
"Correct Solution: ``` import sys int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] def main(): n, m = MI() xx = set([0]) yy = set([0]) vl = [] hl = [] for _ in range(n): a, b, c = MI() xx.add(a) xx.add(b) yy.add(c) vl.append((a, b, c)) for _ in range(m): a, b, c = MI() xx.add(a) yy.add(b) yy.add(c) hl.append((b, c, a)) dex = list(sorted(xx)) dey = list(sorted(yy)) cox = {x: i for i, x in enumerate(dex)} coy = {x: i for i, x in enumerate(dey)} h = len(dex) w = len(dey) vlt=[[1]*w for _ in range(h)] for x0, x1, y in vl: j = coy[y] for i in range(cox[x0], cox[x1]): vlt[i][j]=0 hlt=[[1]*w for _ in range(h)] for y0, y1, x in hl: i = cox[x] for j in range(coy[y0], coy[y1]): hlt[i][j]=0 #p2D(vlt) #print() #p2D(hlt) tt = [[False] * w for _ in range(h)] def inf(): print("INF") exit() def move(ni, nj): if tt[ni][nj]: return tt[ni][nj] = True stack.append((ni, nj)) si, sj = cox[0], coy[0] if si==h-1 or sj==w-1:inf() stack = [(si, sj)] tt[si][sj] = True while stack: i, j = stack.pop() ni, nj = i, j - 1 if vlt[i][j]: if nj == -1: inf() move(ni, nj) ni, nj = i, j + 1 if vlt[ni][nj]: if nj == w - 1: inf() move(ni, nj) ni, nj = i - 1, j if hlt[i][j]: if ni == -1: inf() move(ni, nj) ni, nj = i + 1, j if hlt[ni][nj]: if ni == h - 1: inf() move(ni, nj) #p2D(tt) ans = 0 for i in range(h - 1): for j in range(w - 1): if tt[i][j]: ans += (dex[i + 1] - dex[i]) * (dey[j + 1] - dey[j]) print(ans) main() ```
output
1
105,050
15
210,101
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF Submitted Solution: ``` n,m,*l = map(int, open(0).read().split()) l=iter(l) l=list(zip(l,l,l)) l1=l[:n] l2=l[-m:] V=set([float('inf'),-float('inf')]) H=set([float('inf'),-float('inf')]) for a,b,c in l1: V.add(c) H.add(a) H.add(b) for c,a,b in l2: H.add(c) V.add(a) V.add(b) V=sorted(list(V)) H=sorted(list(H)) Vdic={} Hdic={} for i,v in enumerate(V): Vdic[v]=i for i,h in enumerate(H): Hdic[h]=i checkv=[[0]*3001 for i in range(3001)] checkh=[[0]*3001 for i in range(3001)] check=[[0]*3001 for i in range(3001)] for a,b,c in l1: c=Vdic[c] for i in range(Hdic[a],Hdic[b]): checkh[c][i]=1 for c,a,b in l2: c=Hdic[c] for i in range(Vdic[a],Vdic[b]): checkv[i][c]=1 from bisect import bisect_left pv=bisect_left(V,0)-1 ph=bisect_left(H,0)-1 ans=0 stack=[(pv,ph)] check[pv][ph]=1 while stack: v,h=stack.pop() ans+=(V[v+1]-V[v])*(H[h+1]-H[h]) if h!=0 and checkv[v][h]==0 and check[v][h-1]==0: stack.append((v,h-1)) check[v][h-1]=1 if h!=len(H)-2 and checkv[v][h+1]==0 and check[v][h+1]==0: stack.append((v,h+1)) check[v][h+1]=1 if v!=0 and checkh[v][h]==0 and check[v-1][h]==0: stack.append((v-1,h)) check[v-1][h]=1 if v!=len(V)-2 and checkh[v+1][h]==0 and check[v+1][h]==0: stack.append((v+1,h)) check[v+1][h]=1 print("INF" if ans==float('inf') else ans) ```
instruction
0
105,051
15
210,102
Yes
output
1
105,051
15
210,103
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF Submitted Solution: ``` import sys # from itertools import chain, accumulate n, m, *abcdef = map(int, sys.stdin.buffer.read().split()) ver_lines = [] hor_lines = [] x_list = set() y_list = set() n3 = n * 3 for a, b, c in zip(abcdef[0:n3:3], abcdef[1:n3:3], abcdef[2:n3:3]): y_list.add(a) y_list.add(b) x_list.add(c) ver_lines.append((a, b, c)) for d, e, f in zip(abcdef[n3 + 0::3], abcdef[n3 + 1::3], abcdef[n3 + 2::3]): y_list.add(d) x_list.add(e) x_list.add(f) hor_lines.append((d, e, f)) x_list.add(0) y_list.add(0) x_list = sorted(x_list) y_list = sorted(y_list) x_dict = {x: i for i, x in enumerate(x_list, start=1)} y_dict = {y: i for i, y in enumerate(y_list, start=1)} row_real = len(x_list) col_real = len(y_list) row = row_real + 2 col = col_real + 2 banned_up = [0] * (row * col) banned_down = [0] * (row * col) banned_left = [0] * (row * col) banned_right = [0] * (row * col) for a, b, c in ver_lines: if a > b: a, b = b, a ai = y_dict[a] * row bi = y_dict[b] * row j = x_dict[c] banned_left[ai + j] += 1 banned_left[bi + j] -= 1 banned_right[ai + j - 1] += 1 banned_right[bi + j - 1] -= 1 for d, e, f in hor_lines: if e > f: e, f = f, e ri = y_dict[d] * row ej = x_dict[e] fj = x_dict[f] banned_up[ri + ej] += 1 banned_up[ri + fj] -= 1 banned_down[ri - row + ej] += 1 banned_down[ri - row + fj] -= 1 for i in range(1, col): ri0 = row * (i - 1) ri1 = row * i for j in range(1, row): banned_up[ri1 + j] += banned_up[ri1 + j - 1] banned_down[ri1 + j] += banned_down[ri1 + j - 1] banned_left[ri1 + j] += banned_left[ri0 + j] banned_right[ri1 + j] += banned_right[ri0 + j] # banned_up = list(chain.from_iterable(map(accumulate, banned_up_ij))) # banned_down = list(chain.from_iterable(map(accumulate, banned_down_ij))) # banned_left = list(chain.from_iterable(zip(*map(accumulate, banned_left_ij)))) # banned_right = list(chain.from_iterable(zip(*map(accumulate, banned_right_ij)))) # for i in range(col): # print(walls[i * row:(i + 1) * row]) s = row * y_dict[0] + x_dict[0] enable = [-1] * row + ([-1] + [0] * (row - 2) + [-1]) * (col - 2) + [-1] * row # for i in range(col): # print(enable[i * row:(i + 1) * row]) q = [s] moves = [(-row, banned_up), (-1, banned_left), (1, banned_right), (row, banned_down)] while q: c = q.pop() if enable[c] == 1: continue elif enable[c] == -1: print('INF') exit() enable[c] = 1 for dc, banned in moves: if banned[c]: continue nc = c + dc if enable[nc] == 1: continue q.append(nc) # for i in range(col): # print(enable[i * row:(i + 1) * row]) ans = 0 for i in range(col): ri = i * row for j in range(row): if enable[ri + j] != 1: continue t = y_list[i - 1] b = y_list[i] l = x_list[j - 1] r = x_list[j] ans += (b - t) * (r - l) print(ans) ```
instruction
0
105,052
15
210,104
Yes
output
1
105,052
15
210,105
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF Submitted Solution: ``` import sys,queue,math,copy,itertools,bisect,collections,heapq def main(): INF = 10**9 + 1 MOD = 10**9 + 7 LI = lambda : [int(x) for x in sys.stdin.readline().split()] N,M = LI() x = []; y = [] A = [] D = [] for _ in range(N): a,b,c = LI() A.append((a,b,c)) x.append(a); x.append(b) y.append(c); y.append(c) for _ in range(M): d,e,f = LI() D.append((d,e,f)) x.append(d); x.append(d) y.append(e); y.append(f) x.append(-INF); x.append(INF); x.append(0) y.append(-INF); y.append(INF); y.append(0) x.sort(); y.sort() lx = len(x); ly = len(y) fld = [[0] * ly for _ in range(lx)] for a,b,c in A: j = bisect.bisect_left(y,c) for i in range(bisect.bisect_left(x,a),bisect.bisect_left(x,b)): fld[i][j] = 1 for d,e,f in D: i = bisect.bisect_left(x,d) for j in range(bisect.bisect_left(y,e),bisect.bisect_left(y,f)): fld[i][j] = 1 q = [] i = bisect.bisect_left(x,0) j = bisect.bisect_left(y,0) q.append((i,j)) fld[i][j] = 1 ans = 0 while q: i,j = q.pop() ans += (x[i+1]-x[i]) * (y[j+1]-y[j]) for di,dj in ((0,1),(1,0),(0,-1),(-1,0)): if 0 < i+di < lx-1 and 0 < j+dj < ly-1: if fld[i+di][j+dj] == 0: fld[i+di][j+dj] = 1 q.append((i+di,j+dj)) else: print('INF') exit(0) print(ans) if __name__ == '__main__': main() ```
instruction
0
105,053
15
210,106
Yes
output
1
105,053
15
210,107
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF Submitted Solution: ``` import sys,bisect,string,math,time,functools,random,fractions from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter from itertools import permutations,combinations,groupby def Golf():n,*t=map(int,open(0).read().split()) def I():return int(input()) def S_():return input() def IS():return input().split() def LS():return [i for i in input().split()] def LI():return [int(i) for i in input().split()] def LI_():return [int(i)-1 for i in input().split()] def NI(n):return [int(input()) for i in range(n)] def NI_(n):return [int(input())-1 for i in range(n)] def StoLI():return [ord(i)-97 for i in input()] def ItoS(n):return chr(n+97) def LtoS(ls):return ''.join([chr(i+97) for i in ls]) def GI(V,E,ls=None,Directed=False,index=1): org_inp=[];g=[[] for i in range(V)] FromStdin=True if ls==None else False for i in range(E): if FromStdin: inp=LI() org_inp.append(inp) else: inp=ls[i] if len(inp)==2: a,b=inp;c=1 else: a,b,c=inp if index==1:a-=1;b-=1 aa=(a,c);bb=(b,c);g[a].append(bb) if not Directed:g[b].append(aa) return g,org_inp def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1): #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage mp=[boundary]*(w+2);found={} for i in range(h): s=input() for char in search: if char in s: found[char]=((i+1)*(w+2)+s.index(char)+1) mp_def[char]=mp_def[replacement_of_found] mp+=[boundary]+[mp_def[j] for j in s]+[boundary] mp+=[boundary]*(w+2) return h+2,w+2,mp,found def TI(n):return GI(n,n-1) def bit_combination(n,base=2): rt=[] for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s] return rt def gcd(x,y): if y==0:return x if x%y==0:return y while x%y!=0:x,y=y,x%y return y def show(*inp,end='\n'): if show_flg:print(*inp,end=end) YN=['YES','NO'];Yn=['Yes','No'] mo=10**9+7 inf=float('inf') FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb)) l_alp=string.ascii_lowercase #sys.setrecursionlimit(10**7) input=lambda: sys.stdin.readline().rstrip() class Tree: def __init__(self,inp_size=None,ls=None,init=True,index=0): self.LCA_init_stat=False self.ETtable=[] if init: if ls==None: self.stdin(inp_size,index=index) else: self.size=len(ls)+1 self.edges,_=GI(self.size,self.size-1,ls,index=index) return def stdin(self,inp_size=None,index=1): if inp_size==None: self.size=int(input()) else: self.size=inp_size self.edges,_=GI(self.size,self.size-1,index=index) return def listin(self,ls,index=0): self.size=len(ls)+1 self.edges,_=GI(self.size,self.size-1,ls,index=index) return def __str__(self): return str(self.edges) def dfs(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0): q=deque() q.append(x) v=[-1]*self.size v[x]=root_v while q: c=q.pop() for nb,d in self.edges[c]: if v[nb]==-1: q.append(nb) v[nb]=func(v[c],nb,d) return v def EulerTour(self,x): q=deque() q.append(x) self.depth=[None]*self.size self.depth[x]=0 self.ETtable=[] self.ETdepth=[] self.ETin=[-1]*self.size self.ETout=[-1]*self.size cnt=0 while q: c=q.pop() if c<0: ce=~c else: ce=c for nb,d in self.edges[ce]: if self.depth[nb]==None: q.append(~ce) q.append(nb) self.depth[nb]=self.depth[ce]+1 self.ETtable.append(ce) self.ETdepth.append(self.depth[ce]) if self.ETin[ce]==-1: self.ETin[ce]=cnt else: self.ETout[ce]=cnt cnt+=1 return def LCA_init(self,root): self.EulerTour(root) self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf) self.LCA_init_stat=True return def LCA(self,root,x,y): if self.LCA_init_stat==False: self.LCA_init(root) xin,xout=self.ETin[x],self.ETout[x] yin,yout=self.ETin[y],self.ETout[y] a=min(xin,yin) b=max(xout,yout,xin,yin) id_of_min_dep_in_et=self.st.query_id(a,b+1) return self.ETtable[id_of_min_dep_in_et] class SparseTable: # O(N log N) for init, O(1) for query(l,r) def __init__(self,ls,init_func=min,init_idl=float('inf')): self.func=init_func self.idl=init_idl self.size=len(ls) self.N0=self.size.bit_length() self.table=[ls[:]] self.index=[list(range(self.size))] self.lg=[0]*(self.size+1) for i in range(2,self.size+1): self.lg[i]=self.lg[i>>1]+1 for i in range(self.N0): tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)] tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)] self.table+=[tmp] self.index+=[tmp_id] # return func of [l,r) def query(self,l,r): if r>self.size:r=self.size #N=(r-l).bit_length()-1 N=self.lg[r-l] return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]) # return index of which val[i] = func of v among [l,r) def query_id(self,l,r): if r>self.size:r=self.size #N=(r-l).bit_length()-1 N=self.lg[r-l] a,b=self.index[N][l],self.index[N][max(0,r-(1<<N))] if self.table[0][a]==self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]): b=a return b def __str__(self): return str(self.table[0]) def print(self): for i in self.table: print(*i) class Comb: def __init__(self,n,mo=10**9+7): self.fac=[0]*(n+1) self.inv=[1]*(n+1) self.fac[0]=1 self.fact(n) for i in range(1,n+1): self.fac[i]=i*self.fac[i-1]%mo self.inv[n]*=i self.inv[n]%=mo self.inv[n]=pow(self.inv[n],mo-2,mo) for i in range(1,n): self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo return def fact(self,n): return self.fac[n] def invf(self,n): return self.inv[n] def comb(self,x,y): if y<0 or y>x: return 0 return self.fac[x]*self.inv[x-y]*self.inv[y]%mo show_flg=False show_flg=True ans=0 inf=1<<65 n,m=LI() X=[0,inf,-inf] Y=[0,inf,-inf] V=[] H=[] for i in range(n): a,b,c=LI() V.append(((a,b),c)) Y.append(c) X.append(a) X.append(b) n+=2 V.append(((-inf,inf),inf)) V.append(((-inf,inf),-inf)) for i in range(m): a,b,c=LI() H.append((a,(b,c))) X.append(a) Y.append(b) Y.append(c) m+=2 H.append((inf,(-inf,inf))) H.append((-inf,(-inf,inf))) X.sort() xdc={} c=1 for j in sorted(set(X)): xdc[c]=j c+=1 nx=c-1 Y.sort() ydc={} c=1 for j in sorted(set(Y)): ydc[c]=j c+=1 ny=c-1 xdcr=dict(zip(xdc.values(),xdc.keys())) ydcr=dict(zip(ydc.values(),ydc.keys())) mpy=[[0]*(nx+1+1) for i in range(ny+1+1)] mpx=[[0]*(nx+1+1) for i in range(ny+1+1)] for (a,b),c in V: mpx[ydcr[c]][xdcr[a]]+=1 mpx[ydcr[c]][xdcr[b]]+=-1 for i in range(ny+1): for j in range(nx): mpx[i][j+1]+=mpx[i][j] for d,(e,f) in H: mpy[ydcr[e]][xdcr[d]]+=1 mpy[ydcr[f]][xdcr[d]]+=-1 for j in range(nx+1): for i in range(ny): mpy[i+1][j]+=mpy[i][j] v=[[0]*(nx+1) for i in range(ny+1)] q=deque() q.append((xdcr[0],ydcr[0])) v[ydcr[0]][xdcr[0]]=1 while q: cx,cy=q.popleft() ans+=(xdc[cx]-xdc[cx+1])*(ydc[cy]-ydc[cy+1]) for dx,dy in FourNb: nbx=cx+dx nby=cy+dy if (not 0<=nbx<nx) or (not 0<=nby<ny) or v[nby][nbx]==1: continue if dy!=0: if mpx[cy+(dy+1)//2][cx]==0: q.append((nbx,nby)) v[nby][nbx]=1 else: if mpy[cy][cx+(dx+1)//2]==0: q.append((nbx,nby)) v[nby][nbx]=1 if ans>=inf: ans='INF' print(ans) ```
instruction
0
105,054
15
210,108
Yes
output
1
105,054
15
210,109
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF Submitted Solution: ``` from collections import deque import bisect INF = float("inf") N,M = map(int,input().split()) xtic = {0,-INF,INF} ytic = {0,-INF,INF} hor = [] for _ in range(N): a,b,c = map(int,input().split()) hor.append((c,a,b)) xtic.add(a) xtic.add(b) ytic.add(c) ver = [] for _ in range(M): d,e,f = map(int,input().split()) ver.append((d,e,f)) xtic.add(d) ytic.add(e) ytic.add(f) xtic = list(xtic) ytic = list(ytic) xtic.sort() ytic.sort() xdic = {xtic[i]:i+1 for i in range(len(xtic))} ydic = {ytic[i]:i+1 for i in range(len(ytic))} gyaku_xdic = {xdic[k]:k for k in xdic} gyaku_ydic = {ydic[k]:k for k in ydic} hor.sort() ver.sort() hor_dic = {} ver_dic = {} now = None for c,a,b in hor: c,a,b = ydic[c],xdic[a],xdic[b] if c != now: hor_dic[c] = (1<<b) - (1<<a) else: hor_dic[c] |= (1<<b) - (1<<a) now = c now = None for d,e,f in ver: d,e,f = xdic[d],ydic[e],ydic[f] if d != now: ver_dic[d] = (1<<f) - (1<<e) else: ver_dic[d] |= (1<<f) - (1<<e) now = d def is_connected(x,y,dx,dy): if dx == 0: if dy > 0: if hor_wall[y+1][H-1-x]: return False return True else: if hor_wall[y][H-1-x]: return False return True else: if dx > 0: if ver_wall[x+1][W-1-y]: return False return True else: if ver_wall[x][W-1-y]: return False return True def calc_area(x,y): X = gyaku_xdic[x+1] - gyaku_xdic[x] Y = gyaku_ydic[y+1] - gyaku_ydic[y] return X*Y offset = [(1,0),(0,1),(-1,0),(0,-1)] x0 = bisect.bisect(xtic,0) y0 = bisect.bisect(ytic,0) W,H = len(xtic)+1 ,len(ytic)+1 gyaku_xdic[0] = -INF gyaku_ydic[0] = -INF gyaku_xdic[W] = INF gyaku_ydic[H] = INF hor_wall = [0] + [0 for i in range(1,H)] ver_wall = [0] + [0 for i in range(1,W)] for k in hor_dic: hor_wall[k] = hor_dic[k] for k in ver_dic: ver_wall[k] = ver_dic[k] for k in range(len(hor_wall)): listb = list(map(int,list(bin(hor_wall[k])[2:]))) hor_wall[k] = [0 for j in range(H-len(listb))] + listb for k in range(len(ver_wall)): listb = list(map(int,list(bin(ver_wall[k])[2:]))) ver_wall[k] = [0 for j in range(W-len(listb))] + listb d = [[0 for i in range(W)] for j in range(H)] d[y0][x0] = 1 q = deque([(x0,y0)]) area = 0 while q: x,y = q.pop() area += calc_area(x,y) for dx,dy in offset: nx,ny = x+dx,y+dy if 0<=nx<W and 0<=ny<H: if is_connected(x,y,dx,dy): if nx == 0 or ny == 0 or nx == W-1 or ny == H-1: print("INF") exit() if d[ny][nx] == 0: d[ny][nx] = 1 q.append((nx,ny)) else: print(area) ```
instruction
0
105,055
15
210,110
No
output
1
105,055
15
210,111
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF Submitted Solution: ``` #!/usr/bin/env python3 from collections import defaultdict from heapq import heappush, heappop import sys import bisect sys.setrecursionlimit(10**6) input = sys.stdin.buffer.readline # INF = sys.maxsize INF = 10 ** 10 # INF = float("inf") def dp(*x): # debugprint print(*x) # f = open(sys.argv[1]) # input = f.buffer.readline N, M = map(int, input().split()) vlines = defaultdict(list) hlines = defaultdict(list) vticks = {0} hticks = {0} for i in range(N): A, B, C = map(int, input().split()) vlines[C].append((A, B)) hticks.add(C) vticks.update((A, B)) for i in range(M): D, E, F = map(int, input().split()) hlines[D].append((E, F)) vticks.add(D) hticks.update((E, F)) vticks = [-INF] + list(sorted(vticks)) + [INF] hticks = [-INF] + list(sorted(hticks)) + [INF] def up(y): return vticks[bisect.bisect_left(vticks, y) - 1] def down(y): return vticks[bisect.bisect_left(vticks, y) + 1] def left(x): return hticks[bisect.bisect_left(hticks, x) - 1] def right(x): return hticks[bisect.bisect_left(hticks, x) + 1] def area(i, j): width = hticks[i + 1] - hticks[i] height = vticks[j + 1] - vticks[j] return width * height total_area = 0 visited = set() def visit(i, j): global total_area if (i, j) in visited: return # dp("visit: (i,j)", (i, j)) x = hticks[i] y = vticks[j] a = area(i, j) total_area += a visited.add((i, j)) # visit neighbors l = i - 1 if (l, j) not in visited: for a, b in vlines[x]: if a <= y < b: # blocked break else: # can move left to_visit.append((l, j)) u = j - 1 if (i, u) not in visited: for a, b in hlines[y]: if a <= x < b: # blocked break else: # can move up to_visit.append((i, u)) r = i + 1 if (r, j) not in visited: for a, b in vlines[hticks[r]]: if a <= y < b: # blocked break else: # can move left to_visit.append((r, j)) d = j + 1 if (i, d) not in visited: for a, b in hlines[vticks[d]]: if a <= x < b: # blocked break else: # can move up to_visit.append((i, d)) maxH = len(hticks) - 2 maxV = len(vticks) - 2 # dp(": maxH, maxV", maxH, maxV) i = bisect.bisect_left(hticks, 0) j = bisect.bisect_left(vticks, 0) to_visit = [(i, j)] while to_visit: i, j = to_visit.pop() # dp(": (i,j)", (i, j)) if i == 0 or i == maxH or j == 0 or j == maxV: print("INF") break visit(i, j) # dp(": to_visit", to_visit) else: print(total_area) def _test(): import doctest doctest.testmod() ```
instruction
0
105,056
15
210,112
No
output
1
105,056
15
210,113
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF Submitted Solution: ``` #!usr/bin/env python3 import sys import bisect from collections import deque import numpy as np def LI(): return [int(x) for x in sys.stdin.readline().split()] def LIR(n): return np.array([LI() for i in range(n)]) def solve(): n,m = LI() p = LIR(n) q = LIR(m) M = 10**11 M2 = M**2 fx = [-M,0,M] fy = [-M,0,M] for i in range(n): p[i] *= 10 a,b,c = p[i] fy.append(a) fy.append(b) fy.append(b+1) fx.append(c) fx.append(c+1) for i in range(m): q[i] *= 10 d,e,f = q[i] fy.append(d) fy.append(d+1) fx.append(e) fx.append(f) fx.append(f+1) fy = list(set(fy)) fx = list(set(fx)) fy.sort() fx.sort() h = len(fy)+1 w = len(fx)+1 s = np.zeros((h,w)) for a,b,c in p: ai = bisect.bisect_left(fy,a) bi = bisect.bisect_left(fy,b)+1 ci = bisect.bisect_left(fx,c) s[ai][ci] += 1 s[bi][ci] -= 1 s[ai][ci+1] -= 1 s[bi][ci+1] += 1 for d,e,f in q: di = bisect.bisect_left(fy,d) ei = bisect.bisect_left(fx,e) fi = bisect.bisect_left(fx,f)+1 kd = di*w kdd = kd+w s[di][ei] += 1 s[di][fi] -= 1 s[di+1][ei] -= 1 s[di+1][fi] += 1 for j in range(len(fx)): s[:,j+1] += s[:,j] for i in range(len(fy)): s[i+1] += s[i] d = [(1,0),(-1,0),(0,1),(0,-1)] sx = bisect.bisect_left(fx,0) sy = bisect.bisect_left(fy,0) nh,nw = len(fy)-1,len(fx)-1 fx[1] //= 10 fy[1] //= 10 for i in range(1,nw-1): fx[i+1] = fx[i+1]//10 fx[i] = fx[i+1]-fx[i] for i in range(1,nh-1): fy[i+1] = fy[i+1]//10 fy[i] = fy[i+1]-fy[i] fx[0] = -fx[0] fy[0] = -fy[0] ans = fx[sx]*fy[sy] q = deque() q.append((sy,sx)) f = [1]*nh*nw f[sy*nw+sx] = 0 while q: y,x = q.popleft() for dy,dx in d: ny,nx = y+dy,x+dx if 0 <= ny < nh and 0 <= nx < nw: ind = ny*nw+nx if f[ind] and not s[ny][nx]: k = fx[nx]*fy[ny] if k >= M2: print("INF") return ans += k f[ind] = 0 q.append((ny,nx)) print(ans) return #Solve if __name__ == "__main__": solve() ```
instruction
0
105,057
15
210,114
No
output
1
105,057
15
210,115
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead. Constraints * All values in input are integers between -10^9 and 10^9 (inclusive). * 1 \leq N, M \leq 1000 * A_i < B_i\ (1 \leq i \leq N) * E_j < F_j\ (1 \leq j \leq M) * The point (0, 0) does not lie on any of the given segments. Input Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M Output If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) Examples Input 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 Output 13 Input 6 1 -3 -1 -2 -3 -1 1 -2 -1 2 1 4 -2 1 4 -1 1 4 1 3 1 4 Output INF Submitted Solution: ``` n,m,*l = map(int, open(0).read().split()) l=iter(l) l=list(zip(l,l,l)) l1=l[:n] l2=l[-m:] V=set([float('inf'),-float('inf')]) H=set([float('inf'),-float('inf')]) for a,b,c in l1: V.add(c) H.add(a) H.add(b) for c,a,b in l2: H.add(c) V.add(a) V.add(b) V=sorted(list(V)) H=sorted(list(H)) Vdic={} Hdic={} for i,v in enumerate(V): Vdic[v]=i for i,h in enumerate(H): Hdic[h]=i checkv=[[0]*3001 for i in range(3001)] checkh=[[0]*3001 for i in range(3001)] check=[[0]*3001 for i in range(3001)] for a,b,c in l1: c=Vdic[c] for i in range(Hdic[a],Hdic[b]): checkh[c][i]=1 for c,a,b in l2: c=Hdic[c] for i in range(Vdic[a],Vdic[b]): checkv[i][c]=1 from bisect import bisect_left pv=bisect_left(V,0)-1 ph=bisect_left(V,0)-1 ans=0 stack=[(pv,ph)] check[pv][ph]=1 while stack: v,h=stack.pop() ans+=(V[v+1]-V[v])*(H[h+1]-H[h]) if h!=0 and checkv[v][h]==0 and check[v][h-1]==0: stack.append((v,h-1)) check[v][h-1]=1 if h!=len(H)-2 and checkv[v][h+1]==0 and check[v][h+1]==0: stack.append((v,h+1)) check[v][h+1]=1 if v!=0 and checkh[v][h]==0 and check[v-1][h]==0: stack.append((v-1,h)) check[v-1][h]=1 if v!=len(V)-2 and checkh[v+1][h]==0 and check[v+1][h]==0: stack.append((v+1,h)) check[v+1][h]=1 print(ans) ```
instruction
0
105,058
15
210,116
No
output
1
105,058
15
210,117
Provide a correct Python 3 solution for this coding contest problem. A small country called Maltius was governed by a queen. The queen was known as an oppressive ruler. People in the country suffered from heavy taxes and forced labor. So some young people decided to form a revolutionary army and fight against the queen. Now, they besieged the palace and have just rushed into the entrance. Your task is to write a program to determine whether the queen can escape or will be caught by the army. Here is detailed description. * The palace can be considered as grid squares. * The queen and the army move alternately. The queen moves first. * At each of their turns, they either move to an adjacent cell or stay at the same cell. * Each of them must follow the optimal strategy. * If the queen and the army are at the same cell, the queen will be caught by the army immediately. * If the queen is at any of exit cells alone after the army’s turn, the queen can escape from the army. * There may be cases in which the queen cannot escape but won’t be caught by the army forever, under their optimal strategies. Hint On the first sample input, the queen can move to exit cells, but either way the queen will be caught at the next army’s turn. So the optimal strategy for the queen is staying at the same cell. Then the army can move to exit cells as well, but again either way the army will miss the queen from the other exit. So the optimal strategy for the army is also staying at the same cell. Thus the queen cannot escape but won’t be caught. Input The input consists of multiple datasets. Each dataset describes a map of the palace. The first line of the input contains two integers W (1 ≤ W ≤ 30) and H (1 ≤ H ≤ 30), which indicate the width and height of the palace. The following H lines, each of which contains W characters, denote the map of the palace. "Q" indicates the queen, "A" the army,"E" an exit,"#" a wall and "." a floor. The map contains exactly one "Q", exactly one "A" and at least one "E". You can assume both the queen and the army can reach all the exits. 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, output "Queen can escape.", "Army can catch Queen." or "Queen can not escape and Army can not catch Queen." in a line. Examples Input 2 2 QE EA 3 1 QAE 3 1 AQE 5 5 ..E.. .###. A###Q .###. ..E.. 5 1 A.E.Q 5 5 A.... ####. ..E.. .#### ....Q 0 0 Output Queen can not escape and Army can not catch Queen. Army can catch Queen. Queen can escape. Queen can not escape and Army can not catch Queen. Army can catch Queen. Army can catch Queen. Input 2 2 QE EA 3 1 QAE 3 1 AQE 5 5 ..E.. .###. A###Q .###. ..E.. 5 1 A.E.Q 5 5 A.... . ..E.. .#### ....Q 0 0 Output Queen can not escape and Army can not catch Queen. Army can catch Queen. Queen can escape. Queen can not escape and Army can not catch Queen. Army can catch Queen. Army can catch Queen.
instruction
0
105,204
15
210,408
"Correct Solution: ``` from collections import deque, defaultdict import sys readline = sys.stdin.readline write = sys.stdout.write dd = ((-1, 0), (0, -1), (1, 0), (0, 1), (0, 0)) def solve(): W, H = map(int, readline().split()) if W == H == 0: return False S = [readline().strip() for i in range(H)] px = py = qx = qy = 0 rs = [] pp = [] MP = [[0]*W for i in range(H)] for i in range(H): for j, c in enumerate(S[i]): if c == "Q": px = j; py = i elif c == "A": qx = j; qy = i elif c == "E": MP[i][j] = 1 rs.append((j, i)) elif c == "#": MP[i][j] = 2 if c != "#": pp.append((j, i)) mp = {} L = 0 for ax, ay in pp: for bx, by in pp: mp[ax, ay, bx, by, 0] = L L += 1 mp[ax, ay, bx, by, 1] = L L += 1 que1 = deque() ss = [-1]*L cc = [0]*L que = deque([(px, py, qx, qy, 0)]) used = [0]*L used[mp[px, py, qx, qy, 0]] = 1 RG = [[] for i in range(L)] deg = [0]*L while que: ax, ay, bx, by, t = key = que.popleft() k0 = mp[key] if ax == bx and ay == by: que1.append(k0) ss[k0] = 1 continue if t == 0 and MP[ay][ax] == 1: que1.append(k0) ss[k0] = 0 continue if t == 1: for dx, dy in dd: nx = bx + dx; ny = by + dy if not 0 <= nx < W or not 0 <= ny < H or MP[ny][nx] == 2: continue k1 = mp[ax, ay, nx, ny, t^1] deg[k0] += 1 RG[k1].append(k0) if not used[k1]: used[k1] = 1 que.append((ax, ay, nx, ny, t^1)) else: for dx, dy in dd: nx = ax + dx; ny = ay + dy if not 0 <= nx < W or not 0 <= ny < H or MP[ny][nx] == 2: continue k1 = mp[nx, ny, bx, by, t^1] deg[k0] += 1 RG[k1].append(k0) if not used[k1]: used[k1] = 1 que.append((nx, ny, bx, by, t^1)) while que1: v = que1.popleft() s = ss[v]; t = v % 2 if t == 0: for w in RG[v]: if ss[w] != -1: continue if s == 1: que1.append(w) ss[w] = 1 else: deg[w] -= 1 if deg[w] == 0: que1.append(w) ss[w] = 0 else: for w in RG[v]: if ss[w] != -1: continue if s == 0: que1.append(w) ss[w] = 0 else: deg[w] -= 1 if deg[w] == 0: que1.append(w) ss[w] = 1 k0 = mp[px, py, qx, qy, 0] if ss[k0] == -1: write("Queen can not escape and Army can not catch Queen.\n") elif ss[k0] == 0: write("Queen can escape.\n") else: write("Army can catch Queen.\n") return True while solve(): ... ```
output
1
105,204
15
210,409
Provide tags and a correct Python 3 solution for this coding contest problem. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.
instruction
0
105,510
15
211,020
Tags: combinatorics, math Correct Solution: ``` p = 998244353 def power(x, y, p): b = bin(y)[2:] start = x answer = 1 for i in range(len(b)): if b[len(b)-1-i]=='1': answer = (answer*start) % p start = (start*start) % p return answer def get_seq(S): seq = [] n = len(S) for i in range(n): c = S[i] if c=='0': seq.append(i % 2) return seq def process1(seq, my_max): n = len(seq) if n==0: return 1 maybe2 = 0 if seq[-1]==1 and my_max % 2==0: my_count = my_max//2 else: my_count = my_max//2+1 for i in range(1, n): if seq[i-1]==0 and seq[i]==1: maybe2+=1 # print(seq, my_max, maybe2, my_count) num1 = my_count+maybe2 den1 = n #print(num1, den1) if num1 < den1: return 0 num = 1 den = 1 for i in range(den1): num = (num*num1) % p den = (den*den1) % p num1-=1 den1-=1 den2 = power(den, p-2, p) return (num*den2) % p def process(S): n = len(S) seq = get_seq(S) return process1(seq, n-1) t = int(input()) for i in range(t): n = int(input()) S = input() print(process(S)) ```
output
1
105,510
15
211,021
Provide tags and a correct Python 3 solution for this coding contest problem. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.
instruction
0
105,511
15
211,022
Tags: combinatorics, math Correct Solution: ``` def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p t = int(input()) for _ in range(t): n = int(input()) str = input() d = str.count("11") x = str.count('0') ans = ncr(d+x,d,998244353) print(ans) ```
output
1
105,511
15
211,023
Provide tags and a correct Python 3 solution for this coding contest problem. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.
instruction
0
105,512
15
211,024
Tags: combinatorics, math Correct Solution: ``` #######puzzleVerma####### import sys import math mod = 10**9+7 modd= 998244353 LI=lambda:[int(k) for k in input().split()] input = lambda: sys.stdin.readline().rstrip() IN=lambda:int(input()) S=lambda:input() r=range # def pow(x, y, p): # res = 1 # x = x % p # if (x == 0): # return 0 # while (y > 0): # if ((y & 1) == 1): # res = (res * x) % p # y = y >> 1 # x = (x * x) % p # return res def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den,p - 2, p)) % p for t in r(IN()): n=IN() s=S() once=False zero=0 oneone=0 for ele in s: if ele=="1": if once: oneone+=1 once=False else: once=True else: zero+=1 once=False print(ncr(oneone+zero,oneone,modd)) ```
output
1
105,512
15
211,025
Provide tags and a correct Python 3 solution for this coding contest problem. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.
instruction
0
105,513
15
211,026
Tags: combinatorics, math Correct Solution: ``` # _ _ _ # ___ ___ __| | ___ __| |_ __ ___ __ _ _ __ ___ ___ _ __ __| | __ _ # / __/ _ \ / _` |/ _ \/ _` | '__/ _ \/ _` | '_ ` _ \ / _ \ '__|/ _` |/ _` | # | (_| (_) | (_| | __/ (_| | | | __/ (_| | | | | | | __/ | | (_| | (_| | # \___\___/ \__,_|\___|\__,_|_| \___|\__,_|_| |_| |_|\___|_|___\__,_|\__, | # |_____| |___/ from sys import * '''sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') ''' from collections import defaultdict as dd from math import gcd from bisect import * #sys.setrecursionlimit(10 ** 8) def sinp(): return stdin.readline() def inp(): return int(stdin.readline()) def minp(): return map(int, stdin.readline().split()) def linp(): return list(map(int, stdin.readline().split())) def strl(): return list(sinp()) def pr(x): print(x) mod = int(1e9+7) mod = 998244353 def solve(n, r): if n < r: return 0 if not r: return 1 return (pre_process[n] * pow(pre_process[r], mod - 2, mod) % mod * pow(pre_process[n - r], mod - 2,mod) % mod) % mod pre_process = [1 for i in range(int(1e5+6) + 1)] for i in range(1, int(1e5+7)): pre_process[i] = (pre_process[i - 1] * i) % mod for _ in range(inp()): n = inp() s = sinp() cnt = 0 visited = [0 for i in range(n)] for i in range(n): if int(s[i]) == 0: cnt += 1 cnt_val = 0 for i in range(1, n): if int(s[i]) == int(s[i - 1]) == 1 and not visited[i - 1]: cnt_val += 1 visited[i] = 1 pr(solve(cnt + cnt_val, cnt_val)) ```
output
1
105,513
15
211,027
Provide tags and a correct Python 3 solution for this coding contest problem. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.
instruction
0
105,514
15
211,028
Tags: combinatorics, math Correct Solution: ``` import sys,os,io input = sys.stdin.readline # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p for _ in range (int(input())): n = int(input()) a = [int(i) for i in input().strip()] o = [0] z = [0] for i in range (n): if a[i]==1: if z[-1]!=0: z.append(0) o[-1]+=1 else: if o[-1]!=0: o.append(0) z[-1]+=1 for i in range (len(o)): o[i] -= o[i]%2 ones = sum(o)//2 zeroes = sum(z) mod = 998244353 ans = ncr(zeroes+ones, ones, mod) print(ans) ```
output
1
105,514
15
211,029
Provide tags and a correct Python 3 solution for this coding contest problem. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.
instruction
0
105,515
15
211,030
Tags: combinatorics, math Correct Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase import io from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque from collections import Counter import threading #sys.setrecursionlimit(300000) #threading.stack_size(10**8) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now----------------------------------------------------- #mod = 9223372036854775807 class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: max(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) class SegmentTree1: def __init__(self, data, default=0, func=lambda a, b: a+b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) MOD=10**9+7 class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD mod=10**9+7 omod=998244353 #------------------------------------------------------------------------- prime = [True for i in range(10001)] prime[0]=prime[1]=False #pp=[0]*10000 def SieveOfEratosthenes(n=10000): p = 2 c=0 while (p <= n): if (prime[p] == True): c+=1 for i in range(p, n+1, p): #pp[i]=1 prime[i] = False p += 1 #-----------------------------------DSU-------------------------------------------------- class DSU: def __init__(self, R, C): #R * C is the source, and isn't a grid square self.par = range(R*C + 1) self.rnk = [0] * (R*C + 1) self.sz = [1] * (R*C + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = self.find(x), self.find(y) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = yr, xr if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def top(self): # Size of component at ephemeral "source" node at index R*C, # minus 1 to not count the source itself in the size return self.size(len(self.sz) - 1) - 1 #---------------------------------Lazy Segment Tree-------------------------------------- # https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp class LazySegTree: def __init__(self, _op, _e, _mapping, _composition, _id, v): def set(p, x): assert 0 <= p < _n p += _size for i in range(_log, 0, -1): _push(p >> i) _d[p] = x for i in range(1, _log + 1): _update(p >> i) def get(p): assert 0 <= p < _n p += _size for i in range(_log, 0, -1): _push(p >> i) return _d[p] def prod(l, r): assert 0 <= l <= r <= _n if l == r: return _e l += _size r += _size for i in range(_log, 0, -1): if ((l >> i) << i) != l: _push(l >> i) if ((r >> i) << i) != r: _push(r >> i) sml = _e smr = _e while l < r: if l & 1: sml = _op(sml, _d[l]) l += 1 if r & 1: r -= 1 smr = _op(_d[r], smr) l >>= 1 r >>= 1 return _op(sml, smr) def apply(l, r, f): assert 0 <= l <= r <= _n if l == r: return l += _size r += _size for i in range(_log, 0, -1): if ((l >> i) << i) != l: _push(l >> i) if ((r >> i) << i) != r: _push((r - 1) >> i) l2 = l r2 = r while l < r: if l & 1: _all_apply(l, f) l += 1 if r & 1: r -= 1 _all_apply(r, f) l >>= 1 r >>= 1 l = l2 r = r2 for i in range(1, _log + 1): if ((l >> i) << i) != l: _update(l >> i) if ((r >> i) << i) != r: _update((r - 1) >> i) def _update(k): _d[k] = _op(_d[2 * k], _d[2 * k + 1]) def _all_apply(k, f): _d[k] = _mapping(f, _d[k]) if k < _size: _lz[k] = _composition(f, _lz[k]) def _push(k): _all_apply(2 * k, _lz[k]) _all_apply(2 * k + 1, _lz[k]) _lz[k] = _id _n = len(v) _log = _n.bit_length() _size = 1 << _log _d = [_e] * (2 * _size) _lz = [_id] * _size for i in range(_n): _d[_size + i] = v[i] for i in range(_size - 1, 0, -1): _update(i) self.set = set self.get = get self.prod = prod self.apply = apply MIL = 1 << 20 def makeNode(total, count): # Pack a pair into a float return (total * MIL) + count def getTotal(node): return math.floor(node / MIL) def getCount(node): return node - getTotal(node) * MIL nodeIdentity = makeNode(0.0, 0.0) def nodeOp(node1, node2): return node1 + node2 # Equivalent to the following: return makeNode( getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2) ) identityMapping = -1 def mapping(tag, node): if tag == identityMapping: return node # If assigned, new total is the number assigned times count count = getCount(node) return makeNode(tag * count, count) def composition(mapping1, mapping2): # If assigned multiple times, take first non-identity assignment return mapping1 if mapping1 != identityMapping else mapping2 #---------------------------------Pollard rho-------------------------------------------- def memodict(f): """memoization decorator for a function taking a single argument""" class memodict(dict): def __missing__(self, key): ret = self[key] = f(key) return ret return memodict().__getitem__ def pollard_rho(n): """returns a random factor of n""" if n & 1 == 0: return 2 if n % 3 == 0: return 3 s = ((n - 1) & (1 - n)).bit_length() - 1 d = n >> s for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]: p = pow(a, d, n) if p == 1 or p == n - 1 or a % n == 0: continue for _ in range(s): prev = p p = (p * p) % n if p == 1: return math.gcd(prev - 1, n) if p == n - 1: break else: for i in range(2, n): x, y = i, (i * i + 1) % n f = math.gcd(abs(x - y), n) while f == 1: x, y = (x * x + 1) % n, (y * y + 1) % n y = (y * y + 1) % n f = math.gcd(abs(x - y), n) if f != n: return f return n @memodict def prime_factors(n): """returns a Counter of the prime factorization of n""" if n <= 1: return Counter() f = pollard_rho(n) return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f) def distinct_factors(n): """returns a list of all distinct factors of n""" factors = [1] for p, exp in prime_factors(n).items(): factors += [p**i * factor for factor in factors for i in range(1, exp + 1)] return factors def all_factors(n): """returns a sorted list of all distinct factors of n""" small, large = [], [] for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1): if not n % i: small.append(i) large.append(n // i) if small[-1] == large[-1]: large.pop() large.reverse() small.extend(large) return small #---------------------------------Binary Search------------------------------------------ def binarySearch(arr, n,i, key): left = 0 right = n-1 mid = 0 res=n while (left <= right): mid = (right + left)//2 if (arr[mid][i] > key): res=mid right = mid-1 else: left = mid + 1 return res def binarySearch1(arr, n,i, key): left = 0 right = n-1 mid = 0 res=-1 while (left <= right): mid = (right + left)//2 if (arr[mid][i] > key): right = mid-1 else: res=mid left = mid + 1 return res #---------------------------------running code------------------------------------------ t=1 t=int(input()) for _ in range (t): n=int(input()) #n,m=map(int,input().split()) #a=list(map(int,input().split())) #tp=list(map(int,input().split())) s=input() groups=0 zeros=0 ones=0 for i in s: if i=='0': groups+=ones//2 ones=0 zeros+=1 else: ones+=1 groups+=ones//2 S=Combination(omod) print(S.ncr(groups+zeros, groups)) ```
output
1
105,515
15
211,031
Provide tags and a correct Python 3 solution for this coding contest problem. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.
instruction
0
105,516
15
211,032
Tags: combinatorics, math Correct Solution: ``` import os, sys from io import BytesIO, IOBase from math import log2, ceil, sqrt, gcd from _collections import deque import heapq as hp from bisect import bisect_left, bisect_right BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") mod = 998244353 MX = 10**5+1 fact = [1] for i in range(1, MX): fact.append(fact[-1] * i % mod) inv = [pow(fact[i], mod - 2, mod) for i in range(MX)] for _ in range(int(input())): n=int(input()) ar=input() a=ar.count('0') b=0 i=0 while i<n: if ar[i]=='1': if i+1<n and ar[i+1]=='1': b+=1 i+=2 else: i+=1 else: i+=1 if b==0: print(1) continue ans=fact[a+b] ans*=inv[a] ans%=mod ans*=inv[b] ans%=mod print(ans) ```
output
1
105,516
15
211,033
Provide tags and a correct Python 3 solution for this coding contest problem. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.
instruction
0
105,517
15
211,034
Tags: combinatorics, math Correct Solution: ``` mod = 998244353 import sys input = sys.stdin.readline def ncr(n, r): return ((fact[n]*pow(fact[r]*fact[n-r], mod-2, mod))%mod) fact = [1, 1] for i in range(2, 100010): fact.append((fact[-1]*i)%mod) for nt in range(int(input())): n = int(input()) s = input() i = 0 o, z = 0, 0 while i<n: if s[i]=="0": z += 1 i += 1 elif s[i]=="1" and s[i+1]=="1": o += 1 i += 2 else: i += 1 # print (z+o, o) print (ncr(z+o, o)) ```
output
1
105,517
15
211,035
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations. Submitted Solution: ``` '''input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 ''' from sys import stdin, stdout from collections import defaultdict def combination(a, b): return (((factorial[a] * inverseFact[b]) % mod) * inverseFact[a - b]) % mod mod = 998244353 def inverse(num, mod): if num == 1: return 1 return inverse(mod % num, mod) * (mod - mod//num) % mod factorial = [1 for x in range(10** 5 + 1)] inverseFact = [1 for x in range(10** 5 + 1)] for i in range(2,len(factorial)): factorial[i] = (i * factorial[i - 1]) % mod inverseFact[i] = (inverse(i, mod) * inverseFact[i - 1]) % mod # main starts t = int(stdin.readline().strip()) for _ in range(t): n = int(stdin.readline().strip()) string = stdin.readline().strip() onePair = 0 zero = 0 i = 0 while i < n: if string[i] == '1': if i + 1 < n and string[i + 1] == '1': onePair += 1 i += 2 else: i += 1 else: zero += 1 i += 1 print(combination(onePair + zero, onePair)) ```
instruction
0
105,518
15
211,036
Yes
output
1
105,518
15
211,037
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations. Submitted Solution: ``` import sys input=sys.stdin.readline max_n=10**5 fact, inv_fact = [0] * (max_n+1), [0] * (max_n+1) fact[0] = 1 mod=998244353 def make_nCr_mod(): global fact global inv_fact for i in range(max_n): fact[i + 1] = fact[i] * (i + 1) % mod inv_fact[-1] = pow(fact[-1], mod - 2, mod) for i in reversed(range(max_n)): inv_fact[i] = inv_fact[i + 1] * (i + 1) % mod make_nCr_mod() def nCr_mod(n, r): global fact global inv_fact res = 1 while n or r: a, b = n % mod, r % mod if(a < b): return 0 res = res * fact[a] % mod * inv_fact[b] % mod * inv_fact[a - b] % mod n //= mod r //= mod return res t=int(input()) for _ in range(t): length=int(input()) l=input().rstrip() r=0 tmp=1 for i in range(1,length): if(l[i]=='0'): continue if(l[i]==l[i-1]=='1'): tmp+=1 else: r+=(tmp//2) tmp=1 r+=(tmp//2) n=l.count('0') print(nCr_mod(n+r,r)) ```
instruction
0
105,519
15
211,038
Yes
output
1
105,519
15
211,039
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations. Submitted Solution: ``` N = 100001 factorialNumInverse = [None] * (N + 1) naturalNumInverse = [None] * (N + 1) fact = [None] * (N + 1) def InverseofNumber(p): naturalNumInverse[0] = naturalNumInverse[1] = 1 for i in range(2, N + 1, 1): naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - int(p / i)) % p) def InverseofFactorial(p): factorialNumInverse[0] = factorialNumInverse[1] = 1 for i in range(2, N + 1, 1): factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p def factorial(p): fact[0] = 1 for i in range(1, N + 1): fact[i] = (fact[i - 1] * i) % p def Binomial(N, R, p): ans = ((fact[N] * factorialNumInverse[R])% p * factorialNumInverse[N - R])% p return ans p = 998244353 InverseofNumber(p) InverseofFactorial(p) factorial(p) t=int(input()) while t: t-=1 n=int(input()) s=input() i=a=b=0 while i<n: cnt1=0 while i<n and s[i]=='0': cnt1+=1 i+=1 a+=cnt1 cnt2=0 while i<n and s[i]=='1': cnt2+=1 i+=1 b+=(cnt2//2) print(Binomial(a+b,b,p)) ```
instruction
0
105,520
15
211,040
Yes
output
1
105,520
15
211,041
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations. Submitted Solution: ``` import sys,os,io # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline input = sys.stdin.readline def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p for _ in range (int(input())): n = int(input()) s = list(input().strip()) z = s.count('0') o = 0 co = 0 for i in range (n): if s[i]=='1': co+=1 else: o+=co//2 co=0 o+=co//2 mod = 998244353 print(ncr(z+o, o, mod)) ```
instruction
0
105,521
15
211,042
Yes
output
1
105,521
15
211,043
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations. Submitted Solution: ``` from sys import stdout from math import comb as c def solve(): n = int(input()) a = list(map(int, input())) pair = 0 zeros = 0 cur = 0 for i in range(n): if a[i] == 1: cur += 1 else: pair += cur//2 zeros += 1 cur = 0 pair += cur//2 print(c(pair+zeros, zeros)) stdout.flush() def main(): for _ in range(int(input())): solve() if __name__ == '__main__': main() ```
instruction
0
105,522
15
211,044
No
output
1
105,522
15
211,045
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations. Submitted Solution: ``` mod = 10**9+7 import sys input = sys.stdin.readline def ncr(n, r): return ((fact[n]*pow(fact[r]*fact[n-r], mod-2, mod))%mod) fact = [1, 1] for i in range(2, 100010): fact.append((fact[-1]*i)%mod) for nt in range(int(input())): n = int(input()) s = input() i = 0 o, z = 0, 0 while i<n: if s[i]=="0": z += 1 i += 1 elif s[i]=="1" and s[i+1]=="1": o += 1 i += 2 else: i += 1 print (ncr(z+o, o)) ```
instruction
0
105,523
15
211,046
No
output
1
105,523
15
211,047
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations. Submitted Solution: ``` import math inf = 998244353 import sys def mult(a,b): stuff=1 for i in range(a,b+1): stuff=(stuff*i)%inf return stuff input = sys.stdin.readline for _ in range(int(input())): le = int(input()) s = list(map(str,input().strip())) twos = 0 zero = 0 temp = None for i in s: if i == '1' and temp == None: temp=1 elif i == '1' and temp == 1: temp=None twos+=1 else: temp = None zero+=1 print((mult(max(zero,twos)+1,zero+twos)//mult(1,min(zero,twos)))%inf) ```
instruction
0
105,524
15
211,048
No
output
1
105,524
15
211,049
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible): * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied. * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the chessboard. The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353. Example Input 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 Output 3 6 1 1287 1287 715 Note In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations. Submitted Solution: ``` from math import factorial def ncr(n, r): cnt = 1 for i in range(r): cnt = (cnt * (n-r+1+i)) % 998244353 # print(n, r, cnt, cnt/factorial(r)) return (cnt // factorial(r) % 998244353) % 998244353 for t in range(int(input())): n = int(input()) a = input() oc = 0 i = 0 while i < n-1: if a[i] == '1' and a[i+1] == '1': oc += 1 i += 1 i += 1 zc = a.count('0') print(ncr(oc+zc, min(oc, zc)) % 998244353) ```
instruction
0
105,525
15
211,050
No
output
1
105,525
15
211,051
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C
instruction
0
105,581
15
211,162
Tags: implementation Correct Solution: ``` import math def coder(n): cant = math.ceil(n ** 2 / 2) m = list() for i in range(n): if n % 2 == 0 and i % 2 == 0: m.append("C." * (n // 2)) elif n % 2 == 0 and i % 2 != 0: m.append(".C" * (n // 2)) elif n % 2 != 0 and i % 2 == 0: m.append("C." * (n // 2) + "C") elif n % 2 != 0 and i % 2 != 0: m.append(".C" * (n // 2) + ".") return [cant, m] n = int(input().strip()) r = coder(n) print(r[0]) for i in range(n): print(r[1][i]) ```
output
1
105,581
15
211,163
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C
instruction
0
105,582
15
211,164
Tags: implementation Correct Solution: ``` n = int(input()) k = n // 2 print(n * k + (n % 2) * (k + 1)) s = 'C.' * (k + 1) for i in range(n): q = i % 2 print(s[q : n + q]) ```
output
1
105,582
15
211,165
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C
instruction
0
105,583
15
211,166
Tags: implementation Correct Solution: ``` # import sys # sys.stdin=open("input.in",'r') # sys.stdout=open("outp.out",'w') n=int(input()) c='C.' if n%2==0: print(int(n*n/2)) i=0 while i < int(n/2): print(c*int(n/2)) print(c[::-1]*int(n/2)) i+=1 else: print(int((n*n)/2)+1) i=0 while i<int(n/2): print(c*int(n/2)+c[0]) print(c[::-1]*int(n/2)+c[-1]) i+=1 print(c*int(n/2)+c[0]) # for i in range(n): # for j in range(n): # if c==True: # print('C',end='') # c=False # else: # print(".",end='') # c=True # print() # if i %2==0: # c=False # else: # c=True ```
output
1
105,583
15
211,167
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C
instruction
0
105,584
15
211,168
Tags: implementation Correct Solution: ``` #==========3 задание=============== import math n = int(input()) r1 = math.ceil(n/2) r2 = math.floor(n/2) r3 = r1*r1 + r2*r2 print(r3) l = [] l1 = ["C." for i in range(n)] l2 = [".C" for i in range(n)] for i in range(n): l += ["".join(l1)[:n]] l += ["".join(l2)[:n]] l = l[:n] for i in l: print(i) ```
output
1
105,584
15
211,169
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C
instruction
0
105,585
15
211,170
Tags: implementation Correct Solution: ``` x = int(input()) temp = "" for i in range(1,x+1): if i % 2 != 0: temp += ('C.' * (x//2) + 'C' * (x & 1)) else: temp += ('.C' * (x//2) + '.' * (x & 1)) temp += '\n' print(temp.count('C')) print(temp) ```
output
1
105,585
15
211,171
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C
instruction
0
105,586
15
211,172
Tags: implementation Correct Solution: ``` def main(): n = int(input()) total = (n // 2) * n if n % 2 == 0 \ else (n // 2) * n + (n + 1) // 2 print(total) for i in range(n): s = '' if n % 2 == 0: s = 'C.' * (n // 2) if i % 2 == 0 \ else '.C' * (n // 2) else: s = 'C.' * (n // 2) + 'C' if i % 2 == 0 \ else '.C' * (n // 2) + '.' print(s) if __name__ == '__main__': main() ```
output
1
105,586
15
211,173
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C
instruction
0
105,587
15
211,174
Tags: implementation Correct Solution: ``` n = int(input()) m = '' for i in range(n): for j in range(n): if i%2 == 0 and j%2 ==0 : m +='C' elif i%2 != 0 and j%2 !=0 : m +='C' else: m +='.' m +='\n' print(int((n*n)/2+ (n*n)%2)) print(m) ```
output
1
105,587
15
211,175
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C
instruction
0
105,588
15
211,176
Tags: implementation Correct Solution: ``` n=int(input()) p=0 q=0 a=[] b=[] for x in range(1,n+1): a+=['C'] p+=1 if p==n: break a+=['.'] p+=1 if p==n: break #a= for y in range(1,n+1): b+=['.'] q+=1 if q==n: break b+=['C'] q+=1 if q==n: break #b= if n%2==0: print((n*n)//2) p=0 for x in range(1,n+1): print(''.join([str(x) for x in b])) p+=1 #print('') if p==n: break print(''.join([str(x) for x in a])) p+=1 #print('') if p==n: break else: temp=(n*n)//2 print(temp+1) p=0 for x in range(1,n+1): print(''.join([str(x) for x in a])) p+=1 #print('') if p==n: break print(''.join([str(x) for x in b])) p+=1 #print('') if p==n: break ```
output
1
105,588
15
211,177
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C Submitted Solution: ``` n = int(input()) if n%2 == 0: print(n* n//2) for i in range(n//2): print('C.'*(n//2)) print('.C'*(n//2)) else: ans = (n//2)**2 + (n//2+1)**2 print(ans) for i in range(n//2): print('C.'*(n//2) + 'C') print('.C'*(n//2) + '.') print('C.'*(n//2) + 'C') ```
instruction
0
105,589
15
211,178
Yes
output
1
105,589
15
211,179
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C Submitted Solution: ``` a = int(input()) if (a * a) % 2 == 0: print(a * a // 2) for i in range(a): if i % 2 == 0: for i in range(a // 2): print("C.",end="") else: for i in range(a // 2): print(".C",end="") print() else: print(a * a // 2 + 1) for i in range(a): if i % 2 == 0: for i in range(a // 2): print("C.",end="") print("C",end="") else: for i in range(a // 2): print(".C",end="") print(".",end="") print() ```
instruction
0
105,590
15
211,180
Yes
output
1
105,590
15
211,181
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C Submitted Solution: ``` from math import ceil, trunc n = int(input()) k1 = 0 line1 = [] b = True for i in range(n): line1.append('C' if b else '.') k1 += b b = not b line1 = ''.join(line1) k2 = 0 line2 = [] b = False for i in range(n): line2.append('C' if b else '.') k2 += b b = not b line2 = ''.join(line2) print(ceil(n / 2) * k1 + trunc(n / 2) * k2) b = True for i in range(n): print(line1 if b else line2) b = not b ```
instruction
0
105,591
15
211,182
Yes
output
1
105,591
15
211,183
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C Submitted Solution: ``` #!/usr/bin/python3 # -*- coding: <utf-8> -*- import itertools as ittls from collections import Counter import string def sqr(x): return x*x def inputarray(func = int): return map(func, input().split()) # ------------------------------- # ------------------------------- N = int(input()) print( (sqr(N) + 1)//2 ) for i in range(N): if i&1: s = '.C'*(N//2) if N&1: s = s + '.' else: s = 'C.'*(N//2) if N&1: s = s + 'C' print(s) ```
instruction
0
105,592
15
211,184
Yes
output
1
105,592
15
211,185
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C Submitted Solution: ``` n=int(input()) a=[] for i in range(n): if(not i&1): s='' for j in range(n): if(not j&1): s+='C' else: s+='.' a.append(s) else: s='' for j in range(n): if(not j&1): s+='.' else: s+='C' a.append(s) #print(a) for i in a: print(i) ```
instruction
0
105,593
15
211,186
No
output
1
105,593
15
211,187
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C Submitted Solution: ``` n = int(input()) m = n for i in range(n): if i % 2 == 0: for j in range(n): if j % 2 == 0: print("C",end="") elif j % 2 != 0: print(".",end="") elif i % 2 != 0: for j in range(n): if j % 2 == 0: print(".",end="") elif j % 2 != 0: print("C",end="") print() ```
instruction
0
105,594
15
211,188
No
output
1
105,594
15
211,189
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C Submitted Solution: ``` n = int(input()) if n%2 == 0: print((n*n)//2) else: t = n//2 print(t + n + t*t) for j in range(n): for i in range(n): if i%2 == j%2: print('C', end='') else: print('.', end='') print() ```
instruction
0
105,595
15
211,190
No
output
1
105,595
15
211,191
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder. Input The first line contains an integer n (1 ≤ n ≤ 1000). Output On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any. Examples Input 2 Output 2 C. .C Submitted Solution: ``` n = int(input()) print(((n**2)//2) if (n**2) % 2 == 0 else (((n//2)+1)**2 + (n//2)**2)) for i in range(n): for j in range(n): if (i+j) % 2 == 0: print("c", end="") else: print(".", end="") print() ```
instruction
0
105,596
15
211,192
No
output
1
105,596
15
211,193
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera has a strip infinite in both directions and consisting of cells. The cells are numbered by integers. The cell number 0 has a robot. The robot has instructions — the sequence of moves that he must perform. In one move, the robot moves one cell to the left or one cell to the right, according to instructions. Before the robot starts moving, Valera puts obstacles in some cells of the strip, excluding cell number 0. If the robot should go into the cell with an obstacle according the instructions, it will skip this move. Also Valera indicates the finish cell in which the robot has to be after completing the entire instructions. The finishing cell should be different from the starting one. It is believed that the robot completed the instructions successfully, if during the process of moving he visited the finish cell exactly once — at its last move. Moreover, the latter move cannot be skipped. Let's assume that k is the minimum number of obstacles that Valera must put to make the robot able to complete the entire sequence of instructions successfully and end up in some finishing cell. You need to calculate in how many ways Valera can choose k obstacles and the finishing cell so that the robot is able to complete the instructions successfully. Input The first line contains a sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), consisting only of letters "L" and "R". If character si equals "L", then the robot on the i-th move must try to move one cell to the left. If the si-th character equals "R", then the robot on the i-th move must try to move one cell to the right. Output Print a single integer — the required number of ways. It's guaranteed that this number fits into 64-bit signed integer type. Examples Input RR Output 1 Input RRL Output 1 Note In the first sample Valera mustn't add any obstacles and his finishing cell must be cell 2. In the second sample, Valera must add an obstacle in cell number 1, and his finishing cell must be cell number - 1. In this case robot skips the first two moves and on the third move he goes straight from the starting cell to the finishing one. But if Valera doesn't add any obstacles, or adds an obstacle to another cell, then the robot visits the finishing cell more than once. Submitted Solution: ``` def isBounded(bound): global sequence height = 0 minHeight = 0 for c in sequence: height = min(bound, height + c) minHeight = min(height, minHeight) return height <= minHeight sequence = input() length = len(sequence) - 1 d = {"L": -1, "R": 1} if sequence[-1] == "R": d = {"R": -1, "L": 1} sequence = list(map(lambda x: d[x], sequence[:-1])) if isBounded(float("inf")): # I don't have to do nothing print(1) elif not isBounded(0): # I can't do anything print(0) else: fr = 0 to = length while fr + 1 < to: print(fr, to) mid = (fr + to) >> 1 if isBounded(mid): fr = mid else: to = mid print(fr + 1) ```
instruction
0
105,597
15
211,194
No
output
1
105,597
15
211,195