text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide a correct Python 3 solution for this coding contest problem. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 "Correct Solution: ``` class Edge: def __init__(self, dst, weight): self.dst, self.weight = dst, weight def __lt__(self, e): return self.weight > e.weight class Graph: def __init__(self, V): self.V = V self.E = [[] for _ in range(V)] def add_edge(self, src, dst, weight): self.E[src].append(Edge(dst, weight)) class HeavyLightDecomposition: def __init__(self, g, root=0): self.g = g self.vid, self.head, self.heavy, self.parent = [0] * g.V, [-1] * g.V, [-1] * g.V, [-1] * g.V self.dfs(root) self.bfs(root) def dfs(self, root): stack = [(root, -1)] sub, max_sub = [1] * self.g.V, [(0, -1)] * self.g.V used = [False] * self.g.V while stack: v, par = stack.pop() if not used[v]: used[v] = True self.parent[v] = par stack.append((v, par)) stack.extend((e.dst, v) for e in self.g.E[v] if e.dst != par) else: if par != -1: sub[par] += sub[v] max_sub[par] = max(max_sub[par], (sub[v], v)) self.heavy[v] = max_sub[v][1] def bfs(self, root=0): from collections import deque k, que = 0, deque([root]) while que: r = v = que.popleft() while v != -1: self.vid[v], self.head[v] = k, r for e in self.g.E[v]: if e.dst != self.parent[v] and e.dst != self.heavy[v]: que.append(e.dst) k += 1 v = self.heavy[v] def lca(self, u, v): while self.head[u] != self.head[v]: if self.vid[u] > self.vid[v]: u, v = v, u v = self.parent[self.head[v]] else: if self.vid[u] > self.vid[v]: u, v = v, u return u N = int(input()) g = Graph(N) for i in range(N): for c in map(int, input().split()[1:]): g.add_edge(i, c, 1) g.add_edge(c, i, 1) hld = HeavyLightDecomposition(g) Q = int(input()) for _ in range(Q): u, v = map(int, input().split()) print(hld.lca(u, v)) ```
5,000
Provide a correct Python 3 solution for this coding contest problem. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 "Correct Solution: ``` import math def lca(x, y): if d[x] < d[y]: x,y = y,x dy = d[y] k = d[x]-dy#abs(depth) #Align depth while k: x = p[x][int(math.log(k,2))] k = d[x]-dy if x == y: return x for i in range(h)[::-1]: #print(h) if p[x][i] != p[y][i]: x = p[x][i] y = p[y][i] return p[x][0] if __name__ == "__main__": n = int(input()) #depth d = [0] * n d[0] = 1 #parent p = [[] for i in range(n)] p[0].append(0) for i in range(n): vi = map(int, input().split()[1:]) nd = d[i] + 1 for j in vi: p[j].append(i) d[j] = nd #print(p) #print(d) h = int(math.log(max(d),2)) + 1 for i in range(h - 1): for x in range(n): p[x].append(p[p[x][i]][i]) #print(p) q = int(input()) for _ in range(q): x,y = map(int, input().split()) print(lca(x,y)) ```
5,001
Provide a correct Python 3 solution for this coding contest problem. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 "Correct Solution: ``` # -*- coding: utf-8 -*- from functools import lru_cache import sys buff_readline = sys.stdin.buffer.readline readline = sys.stdin.readline INF = 2**60 def read_int(): return int(buff_readline()) def read_int_n(): return list(map(int, buff_readline().split())) class Doubling(): def __init__(self, a0): """ a0 is an array-like object which contains ai, 0 <= i < N. ai is the next value of i. """ N = len(a0) self.N = N self.nt = [[None] * N for i in range(N.bit_length()+1)] for i, a in enumerate(a0): self.nt[0][i] = a for i in range(1, len(self.nt)): for j in range(N): if self.nt[i-1][j] is None: self.nt[i][j] = None else: self.nt[i][j] = self.nt[i-1][self.nt[i-1][j]] def apply(self, i, n): """ Apply n times from i """ j = i for k in range(n.bit_length()): m = 1 << k if m & n: j = self.nt[k][j] if j is None: break return j class LCA(): def __init__(self, g, root): s = [root] self.N = len(g) self.p = [None] * self.N self.d = [INF] * self.N self.p[root] = root self.d[root] = 0 while s: u = s.pop() for v in g[u]: if self.d[v] is INF: self.p[v] = u self.d[v] = self.d[u] + 1 s.append(v) self.doubling = Doubling(self.p) def query(self, u, v): if self.d[u] > self.d[v]: u, v = v, u o = self.d[v] - self.d[u] v = self.doubling.apply(v, o) if u == v: return u for k in range(len(self.doubling.nt)-1, -1, -1): if self.doubling.nt[k][u] != self.doubling.nt[k][v]: u = self.doubling.nt[k][u] v = self.doubling.nt[k][v] return self.doubling.nt[0][u] def slv(N, KC, Q, UV): g = [list() for _ in range(N)] for u, (k, *c) in enumerate(KC): for v in c: g[u].append(v) g[v].append(u) lca = LCA(g, 0) ans = [] for u, v in UV: i = lca.query(u, v) ans.append(i) return ans def main(): N = read_int() KC = [read_int_n() for _ in range(N)] Q = read_int() UV = [read_int_n() for _ in range(Q)] print(*slv(N, KC, Q, UV), sep='\n') if __name__ == '__main__': main() ```
5,002
Provide a correct Python 3 solution for this coding contest problem. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 "Correct Solution: ``` class Lca: def __init__(self, E, root): import sys sys.setrecursionlimit(500000) self.root = root self.E = E # V<V> self.n = len(E) # 頂点数 self.logn = 1 # n < 1<<logn ぴったりはだめ while self.n >= (1<<self.logn): self.logn += 1 # parent[n][v] = ノード v から 1<<n 個親をたどったノード self.parent = [[-1]*self.n for _ in range(self.logn)] self.depth = [0] * self.n self.dfs(root, -1, 0) for k in range(self.logn-1): for v in range(self.n): p_ = self.parent[k][v] if p_ >= 0: self.parent[k+1][v] = self.parent[k][p_] def dfs(self, v, p, dep): # ノード番号、親のノード番号、深さ self.parent[0][v] = p self.depth[v] = dep for e in self.E[v]: if e != p: self.dfs(e, v, dep+1) def get(self, u, v): if self.depth[u] > self.depth[v]: u, v = v, u # self.depth[u] <= self.depth[v] dep_diff = self.depth[v]-self.depth[u] for k in range(self.logn): if dep_diff >> k & 1: v = self.parent[k][v] if u==v: return u for k in range(self.logn-1, -1, -1): if self.parent[k][u] != self.parent[k][v]: u = self.parent[k][u] v = self.parent[k][v] return self.parent[0][u] n = int(input()) E = [[] for _ in range(n)] for i in range(n): kc = list(map(int, input().split())) k = kc[0] for c in kc[1:]: E[i].append(c) E[c].append(i) lca = Lca(E, 0) Q = int(input()) for _ in range(Q): u, v = map(int, input().split()) print(lca.get(u, v)) ```
5,003
Provide a correct Python 3 solution for this coding contest problem. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 "Correct Solution: ``` from math import log2 class LCA: N = 0 depth = [] table = [] def init(N, par): LCA.N = N LCA.depth = [-1] * (N+1) max_depth = 0 # set depth for i in range(1, N+1): if LCA.depth[i] != -1: continue q = [] v = i while True: q.append(v) if v == par[v]: d = 1 break if LCA.depth[v] != -1: d = LCA.depth[v] break v = par[v] for v in q[::-1]: LCA.depth[v] = d d += 1 max_depth = max(max_depth, d) t_size = int(log2(max_depth))+1 LCA.table = [[i for i in range(N+1)] for j in range(t_size)] for i in range(N+1): LCA.table[0][i] = par[i] for i in range(1, t_size): for j in range(1, N+1): LCA.table[i][j] = LCA.table[i-1][LCA.table[i-1][j]] def move(v, m): # v の m代の祖先 i = 0 while m: if m % 2: v = LCA.table[i][v] i += 1 m //= 2 return v def same(v, u): # v と uのLCA v_d = LCA.depth[v] u_d = LCA.depth[u] if v_d > u_d: v, u = u, v v_d, u_d = u_d, v_d diff = u_d - v_d u = LCA.move(u, diff) if v == u: return v l, r = 1, v_d while l < r: mid = (l+r) // 2 v_p = LCA.move(v, mid) u_p = LCA.move(u, mid) if v_p == u_p: r = mid else: l = mid+1 return LCA.move(v, l) def same2(v, u): # v の祖先に u がいるか if v == u: return True v_d = LCA.depth[v] u_d = LCA.depth[u] if v_d <= u_d: return False if LCA.move(v, v_d-u_d) == u: return True else: return False N = int(input()) par = [i for i in range(N+1)] for i in range(N): c = list(map(int, input().split())) for j in c[1:]: par[j] = i LCA.init(N, par) for i in range(int(input())): a, b = list(map(int, input().split())) print(LCA.same(a, b)) ```
5,004
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` from math import log2 def build(): global parent dfs() pk0 = parent[0] for pk1 in parent[1:]: for v in range(n): pkv = pk0[v] pk1[v] = -1 if pkv < 0 else pk0[pkv] pk0 = pk1 def dfs(): global depth, parent, tree stack = [(0, -1, 0)] while stack: v, p, d = stack.pop() parent[0][v] = p depth[v] = d stack.extend((child, v, d + 1) for child in tree[v]) def lca(u: int, v: int) -> int: global depth, parent du, dv = depth[u], depth[v] if du > dv: u, v = v, u du, dv = dv, du for k, pk in enumerate(parent): if (dv - du) >> k & 1: v = pk[v] if u == v: return u for pk in parent[logn - 1:None:-1]: pku, pkv = pk[u], pk[v] if pku != pkv: u, v = pku, pkv return parent[0][u] if __name__ == "__main__": n = int(input()) tree = [] for _ in range(n): _, *children = map(lambda x: int(x), input().split()) tree.append(set(children)) logn = int(log2(n)) + 1 parent = [[0] * n for _ in range(logn)] depth = [0] * n build() q = int(input()) for _ in range(q): u, v = map(lambda x: int(x), input().split()) print(lca(u, v)) ``` Yes
5,005
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` import sys,math sys.setrecursionlimit(1000000) INF = float("inf") N = int(sys.stdin.readline()) c = tuple(tuple(map(int,sys.stdin.readline().rstrip().split()))[1:] for _ in range(N)) # multi line with multi param Q = int(sys.stdin.readline()) uv = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(Q)) # multi line with multi param G = [list() for _ in range(N)] for i,children in enumerate(c): G[i] = children square = [i**2 for i in range(i,40)] import bisect #LN = bisect.bisect_left(square,N)+2 LN = math.ceil(math.log2(N))+1 depth = [0]*N parents = [[0]*N for _ in range(LN)] def dfs(v,p,l): parents[0][v] = p depth[v] = l for i in G[v]: if i != p: dfs(i,v,l+1) dfs(0,-1,0) for k in range(LN-1):#-1? for v in range(N): if parents[k][v] < 0: parents[k+1][v] = -1 else: parents[k+1][v] = parents[k][parents[k][v]] def query(u,v): if depth[u] > depth[v]: u,v = v,u while depth[v] != depth[u]: v = parents[int(math.log2(depth[v]-depth[u]))][v] # for k in range(LN)[::-1]: # if ((depth[v]-depth[u])>>k & 1): # v = parents[k][v] assert(depth[u]==depth[v]) if u == v: return u for k in range(LN)[::-1]: if parents[k][v] != parents[k][u]: v = parents[k][v] u = parents[k][u] return parents[0][u] ans = [] for u,v in uv: print(query(u,v)) ``` Yes
5,006
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` #!/usr/bin/env python3 # GRL_5_C: Tree - Lowest Common Ancestor class UnionFind: def __init__(self, n): self.nodes = [i for i in range(n)] self.sizes = [1 for _ in range(n)] def union(self, p, q): rp = self.root(p) rq = self.root(q) if self.sizes[rp] > self.sizes[rq]: self.nodes[rq] = rp self.sizes[rp] += self.sizes[rq] else: self.nodes[rp] = rq self.sizes[rq] += self.sizes[rp] def connected(self, p, q): return self.root(p) == self.root(q) def root(self, p): while p != self.nodes[p]: self.nodes[p] = self.nodes[self.nodes[p]] p = self.nodes[p] return p class Edge: __slots__ = ('v', 'w') def __init__(self, v, w): self.v = v self.w = w def either(self): return self.v def other(self, v): if v == self.v: return self.w else: return self.v class WeightedEdge(Edge): __slots__ = ('v', 'w', 'weight') def __init__(self, v, w, weight): super().__init__(v, w) self.weight = weight class Graph: def __init__(self, v): self.v = v self._edges = [[] for _ in range(v)] def add(self, e): self._edges[e.v].append(e) self._edges[e.w].append(e) def adj(self, v): return self._edges[v] def edges(self): for es in self._edges: for e in es: yield e def lca(graph, root, queries): index = [set() for _ in range(graph.v)] for v, w in queries: index[v].add((v, w)) visited = [False] * graph.v stored = [False] * graph.v parents = [None] * graph.v uf = UnionFind(graph.v) res = {} stack = [root] while stack: v = stack.pop() if not visited[v]: visited[v] = True stack.append(v) for e in graph.adj(v): w = e.other(v) if not visited[w]: stack.append(w) parents[w] = v else: stored[v] = True p = parents[v] rest = set() for i, j in index[v]: if stored[i] and stored[j]: if uf.connected(i, j) and (i, j) not in res: res[(i, j)] = v else: rest.add((i, j)) else: index[j].add((i, j)) index[v] = None if p is not None: uf.union(p, v) index[p].update(rest) return res def run(): n = int(input()) g = Graph(n) for i in range(n): k, *cs = [int(i) for i in input().split()] if k > 0: for j in cs: g.add(Edge(i, j)) q = int(input()) qs = [] for _ in range(q): v, w = [int(i) for i in input().split()] qs.append((v, w)) res = lca(g, 0, qs) for v, w in qs: print(res[(v, w)]) if __name__ == '__main__': run() ``` Yes
5,007
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` # 参考 https://tjkendev.github.io/procon-library/python/graph/lca-segment-tree.html # N: 頂点数 # G[v]: 頂点vの子頂点 (親頂点は含まない) import sys sys.setrecursionlimit(10**7) N = int(input()) G = [[] for _ in range(N)] for v in range(N): for j, nv in enumerate(map(int, input().split())): if j == 0: continue G[v].append(nv) # Euler Tour の構築 S = [] F = [0]*N depth = [0]*N def dfs(v, d): F[v] = len(S) depth[v] = d S.append(v) for w in G[v]: dfs(w, d+1) S.append(v) dfs(0, 0) # 存在しない範囲は深さが他よりも大きくなるようにする INF = (N, None) # LCAを計算するクエリの前計算 M = 2*N M0 = 2**(M-1).bit_length() data = [INF]*(2*M0) for i, v in enumerate(S): data[M0-1+i] = (depth[v], i) for i in range(M0-2, -1, -1): data[i] = min(data[2*i+1], data[2*i+2]) # LCAの計算 (generatorで最小値を求める) def _query(a, b): yield INF a += M0; b += M0 while a < b: if b & 1: b -= 1 yield data[b-1] if a & 1: yield data[a-1] a += 1 a >>= 1; b >>= 1 # LCAの計算 (外から呼び出す関数) def query(u, v): fu = F[u]; fv = F[v] if fu > fv: fu, fv = fv, fu return S[min(_query(fu, fv + 1))[1]] ans_list = [] q = int(input()) for _ in range(q): u, v = map(int, input().split()) ans = query(u, v) ans_list.append(ans) print(*ans_list, sep="\n") ``` Yes
5,008
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` import math from collections import defaultdict def dfs(here, p, d, parent, depth, connect): parent[0][here] = p depth[here] = d for next_v in connect[here]: dfs(next_v, here, d + 1, parent, depth, connect) def lca(v1, v2, parent): v1, v2 = max(v1, v2), min(v1, v2) for i in range(max_log): if depth[v1] - depth[v2] >> i & 1: v1 = parent[i][v1] if v1 == v2: return v2 for i in range(max_log - 1, -1, -1): if parent[i][v1] != parent[i][v2]: v1 = parent[i][v1] v2 = parent[i][v2] return parent[0][v2] connect = defaultdict(list) v_num = int(input()) root = 0 for i in range(v_num): edge = [int(n) for n in input().split(" ")] connect[i].extend(edge[1:]) depth = [-1 for n in range(v_num)] max_log = int(math.log(v_num, 2)) parent = [[-1 for n in range(v_num)] for m in range(max_log)] dfs(root, -1, 0, parent, depth, connect) for i in range(max_log - 1): for v in range(v_num): parent[i + 1][v] = -1 if parent[i][v] < 0 else parent[i][parent[i][v]] q_num = int(input()) for _ in range(q_num): v1, v2 = (int(n) for n in input().split(" ") ) print(lca(v1, v2, parent)) ``` No
5,009
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` #!/usr/bin/env python3 # GRL_5_C: Tree - Lowest Common Ancestor # Post Order順を使用して判定する # q = 100000では3分近くかかり、実用に耐えず class Edge: __slots__ = ('v', 'w') def __init__(self, v, w): self.v = v self.w = w def either(self): return self.v def other(self, v): if v == self.v: return self.w else: return self.v class Graph: def __init__(self, v): self.v = v self._edges = [[] for _ in range(v)] def add(self, e): self._edges[e.v].append(e) self._edges[e.w].append(e) def adj(self, v): return self._edges[v] def edges(self): for es in self._edges: for e in es: yield e class LowestCommonAncestor: def __init__(self, graph, root): self.graph = graph self.root = root self._cache = {} self._dfs() def _dfs(self): n = self.graph.v visited = [False] * n parent = [None] * n post_order = [0] * n stack = [self.root] i = 0 while stack: v = stack.pop() if not visited[v]: visited[v] = True stack.append(v) for e in self.graph.adj(v): w = e.other(v) if not visited[w]: parent[w] = v stack.append(w) else: post_order[v] = i i += 1 self.post_order = post_order self.parent = parent def find(self, v, w): pos = self.post_order i = pos[v] j = pos[w] if i > j: i, j = j, i v, w = w, v vv = v while i < j: if (vv, w) in self._cache: vv = self._cache[(vv, w)] break vv = self.parent[vv] i = pos[vv] self._cache[(v, w)] = vv return vv def run(): n = int(input()) g = Graph(n) for i in range(n): k, *cs = [int(i) for i in input().split()] if k > 0: for j in cs: g.add(Edge(i, j)) lca = LowestCommonAncestor(g, 0) q = int(input()) for _ in range(q): v, w = [int(i) for i in input().split()] print(lca.find(v, w)) if __name__ == '__main__': run() ``` No
5,010
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` from sys import stdin from collections import defaultdict readline = stdin.readline def main(): n = int(readline()) g = dict() for i in range(n): nodes = list(map(int, readline().split())) g[i] = nodes[1:] print(g) euler, height = euler_tour(g, n) index = defaultdict(list) for i in range(len(euler)): index[euler[i]].append(i) rmql = [(height[i], i) for i in euler] rmq = segment_tree(rmql,min,(float('inf'),)) q = int(readline()) for i in range(q): u, v = map(int, readline().split()) l, r = index[u][0], index[v][-1] if l > r: l, r = index[v][0], index[u][-1] print(rmq.find(l, r)[1]) def euler_tour(g, size): height = [None] * size euler = [] root = 0 dfs_stack = [(root, None, 0)] while dfs_stack: u, prev, h = dfs_stack.pop() height[u] = h euler.append(prev) if g[u]: dfs_stack.extend((v, u, h + 1) for v in g[u]) else: euler.append(u) return euler[1:], height import math class segment_tree: def __init__(self, dat, query, default=0): self.offset = 2 ** math.ceil(math.log(len(dat), 2)) self.table = [default] * self.offset + dat + [default] * (self.offset - len(dat)) self.query = query for i in reversed(range(1, self.offset)): self.table[i] = self.query(self.table[2 * i], self.table[2 * i + 1]) # [l, r] closed-interval def find(self, l, r): return self.query(self.__range(l,r)) def __range(self, l, r): l += self.offset r += self.offset while l <= r: if l & 1: yield self.table[l] l += 1 l >>= 1 if r & 1 == 0: yield self.table[r] r -= 1 r >>= 1 def update(self, i, x): i += self.offset self.table[i] = x while 1 < i: i >>= 1 self.table[i] = self.query(self.table[2 * i], self.table[2 * i + 1]) main() ``` No
5,011
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a rooted tree, find the lowest common ancestor of two nodes u and v. The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 Input n k0 c1 c2 ... ck0 k1 c1 c2 ... ck1 : kn-1 c1 c2 ... ckn-1 q u1 v1 u2 v2 : uq vq The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i. In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries. Output For each query, print the LCA of u and v in a line. Example Input 8 3 1 2 3 2 4 5 0 0 0 2 6 7 0 0 4 4 6 4 7 4 3 5 2 Output 1 1 0 0 Submitted Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 16 3 1 2 3 3 4 5 6 0 2 7 8 0 2 9 10 2 14 15 0 0 0 3 11 12 13 0 0 0 0 0 10 1 3 4 5 4 9 4 10 4 13 9 13 9 14 9 8 13 14 13 7 output: 0 1 1 1 1 5 1 0 1 0 """ import sys import math sys.setrecursionlimit(int(1e5)) def dfs(v, v_parent, v_depth): # print(parent, v, v_parent) parent[0][v] = v_parent depth[v] = v_depth for adj in adj_table[v]: if adj != v_parent: dfs(adj, v, v_depth + 1) return None def dfs_init(): dfs(root, -1, 0) for k in range(v_log - 1): for v in range(v_num): if parent[k][v] < 0: parent[k + 1][v] = -1 else: parent[k + 1][v] = parent[k][parent[k][v]] return None def lca(u, v): if depth[u] > depth[v]: u, v = v, u for k in range(v_log): if ((depth[v] - depth[u]) >> k) & 1: v = parent[k][v] if u == v: return u for k in range(v_log - 1, -1, -1): if parent[k][u] != parent[k][v]: u = parent[k][u] v = parent[k][v] return parent[0][u] def cmd_exec(): for query in c_queries: q1, q2 = map(int, query) print(lca(q1, q2)) return None if __name__ == '__main__': # with open('test.txt', 'r') as f: # _input = f.readlines() _input = sys.stdin.readlines() v_num = int(_input[0]) c_edges = map(lambda x: x.split(), _input[1:v_num + 1]) q_num = int(_input[v_num + 1]) c_queries = map(lambda x: x.split(), _input[v_num + 2:]) v_log = math.floor(math.log2(v_num)) + 1 parent = [[-1] * v_num for _ in range(v_log)] depth = [-1] * v_num root = 0 adj_table = tuple([] for _ in range(v_num)) for idx, edge in enumerate(c_edges): c_num, *children = map(int, edge) assert len(children) == c_num adj_table[idx].extend(children) dfs_init() cmd_exec() ``` No
5,012
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Tags: brute force, implementation Correct Solution: ``` n, m, q = map(int, input().split()) s = input() t = input() flag = [0]*(1007) prefix = [0]*(1007) for i in range(n-m+1): f = 1 for j in range(m): if s[i+j] != t[j]: f = 0 flag[i]= f prefix[i+1]= prefix[i]+flag[i] for i in range(max(0,n-m+1), n): prefix[i+1] = prefix[i] for _ in range(q): l, r = map(int, input().split()) l -= 1 r -= (m - 1) print(prefix[r] - prefix[l]) if r >= l else print(0) ```
5,013
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Tags: brute force, implementation Correct Solution: ``` string = "" array = [] n, m, q = map(int, input().split()) s = input() t = input() for i in range(0, n - m + 1) : if s[ i : i + m] == t : string += '1' else : string += '0' for i in range(0, q) : a, b = map(int, input().split()) if b - a + 1 >= m : array.append((string[ a - 1: b - m + 1]).count('1')) else : array.append(0) for i in range(0, q) : print(array[i], end = '\n') ```
5,014
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Tags: brute force, implementation Correct Solution: ``` n, m, q = [int(i) for i in input().split()] s = input() t = input() positions = '' for i in range(n-m+1): if s[i:i + m] == t: positions += '1' else: positions += '0' for i in range(q): l,r = map(int, input().split()) if r - l + 1 >= m: print (positions[l-1:r-m+1].count('1')) else: print(0) ```
5,015
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Tags: brute force, implementation Correct Solution: ``` n,m,q = map(int,input().split()) s = input() t = input() l = [] r = [] for i in range(n-m+1): if s[i:i+m] == t: l.append(i) r.append(i+m-1) for i in range(q): x,y = map(int,input().split()) x-=1 y-=1 ans = 0 for j in range(len(l)): if x <= l[j] and y >= r[j]: ans+=1 print(ans) ```
5,016
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Tags: brute force, implementation Correct Solution: ``` def read(): return int(input()) def readlist(): return list(map(int, input().split())) def readmap(): return map(int, input().split()) n, m, q = readmap() S = input() T = input() L = [] R = [] for _ in range(q): l, r = readmap() L.append(l) R.append(r) left = [0] * n right = [0] * n for i in range(n-m+1): if S[i:i+m] == T: for j in range(i+1, n): left[j] += 1 for j in range(i+m-1, n): right[j] += 1 for i in range(q): l, r = L[i], R[i] print(max(0, right[r-1] - left[l-1])) ```
5,017
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Tags: brute force, implementation Correct Solution: ``` n,m,q = map(int, input().split()) s = input() t =input() res="" if n>=m: for i in range(n): if (s[i:i+m]==t): res+="1" else: res+="0" for i in range(q): c0,c1 = map(int, input().split()) if (m>n) or (c1-c0+1<m): print (0) else : print (res[c0-1:c1-m+1].count("1")) ```
5,018
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Tags: brute force, implementation Correct Solution: ``` n,m,q=map(int,input().split()) s,t=input(),input() a=[0,0] b=0 for i in range(n): b+=s[i:i+m]==t a+=[b] for _ in[0]*q: l,r=map(int,input().split()) print(a[max(l,r-m+2)]-a[l]) ```
5,019
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Tags: brute force, implementation Correct Solution: ``` n, m, q = map(int, input().split()) s = input() t = input() a = [0] * n for i in range(n - m + 1): if s[i:i + m] == t: a[i] = 1 for i in range(q): k = 0 l, r = map(int, input().split()) for j in range(l - 1, r): if a[j] == 1 and j + m - 1 < r: k += 1 print(k) ```
5,020
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Submitted Solution: ``` import bisect f=lambda: map(int, input().split()) n,m,q=f() s,t=input(),input() x,st=[],[] c1=0 for i in range(n): if "".join(c for c in s[i:i+m])==t: x.append(i+1) c1+=1 for i in range(q): cnt=0 l,r=f() if x!=[] and r-l+1>=m: r=r-m+1 left=bisect.bisect_left(x,l) right=bisect.bisect_left(x,r) if right>=c1: right-=1 if x[right]>r: right-=1 cnt=right-left+1 st.append(str(cnt)) print('\n'.join(st)) ``` Yes
5,021
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Submitted Solution: ``` # n=int(input()) # ns=[int(x) for x in input().split()] # dp=[None]*n # def greater(i,num): # return ns[i]+ns[i+1]>=num # def biSearch(t,l,r): # if r-l<=1: # return l # m=(l+r)//2 # if greater(m,t) # # # def update(t): # l=ns[t] n,m,q=[int(x)for x in input().split()] sn=input() sm=input() def eq(i): for j in range(m): if sn[i+j]!=sm[j]: return False return True re=[0]*n for i in range(n-m+1): if eq(i): re[i]=1 for i in range(1,n): re[i]+=re[i-1] for i in range(q): l,r=[int(x)-1 for x in input().split()] if r-l+1<m: print(0) continue if l==0: print(re[r-m+1]) else: print(re[r-m+1]-re[l-1]) ``` Yes
5,022
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Submitted Solution: ``` n, m, q = list(map(int, input().strip().split())) s = input() t = input() locs = [] for i in range(n): if i + m <= n and s[i:i+m] == t: locs.append(i) #print(locs) def find_max(nums, target): l, r = 0, len(nums) - 1 while l < r: mid = (l + r) // 2 if nums[mid] >= target: r = mid else: l = mid + 1 if nums[l] >= target: return l else: return len(nums) def helper(l, r, nums): if len(nums) == 0: return 0 x = find_max(nums, l) y = find_max(nums, r) if y >= len(nums) or nums[y] > r: return y - x else: return y - x + 1 for i in range(q): l, r = list(map(int, input().strip().split())) l -= 1 r -= 1 if r - m + 1 < l: print(0) else: res = helper(l, r - m + 1, locs) print(res) ``` Yes
5,023
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Submitted Solution: ``` n,m,q=map(int,input().split()) s=input() t=input() k=[0]*(n+1) for i in range(1,n+1): k[i]=k[i-1] if s[i-1:i+m-1]==t:k[i]+=1 for i in range(q): l,r=map(int,input().split()) print(k[max(l-1,r-m+1)]-k[l-1]) ``` Yes
5,024
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Submitted Solution: ``` n, m, q = map(int, input().split()) s = input() t = input() d = [] axis = [0]*n for i in range(0, n-m+1): if s[i:i+m] == t: for x in range(i, i+m): axis[x] = 1 for i in range(q): ans = 0 l, r = map(int, input().split()) print(sum(axis[l-1:r])//m) ``` No
5,025
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Submitted Solution: ``` from sys import stdin def main(): n, m , q = [ int(s) for s in stdin.readline().split(" ")] s = stdin.readline().strip() t = stdin.readline().strip() queries = [] for line in range(0, q) : queries.append( [ int(s) for s in stdin.readline().split(" ")]) for query in queries: if( m <= query[1] - query[0]): print(0) else: cont = 0 for index in range(query[0], (query[1] - m + 2)): if(s[index-1:index+m-1] == t): cont+=1 print(cont) main() ``` No
5,026
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Submitted Solution: ``` string = "" array = [] n, m, q = map(int, input().split()) s = input() t = input() for i in range(0, n - m + 1) : if s[ i : i + m] == t : string += '1' else : string += '0' for i in range(0, q) : a, b = map(int, input().split()) if a - b + 1 >= m : array.append(string[ a - 1: b - m + 1].count("1")) else : array.append(0) for i in range(0, q) : print(array[i]) ``` No
5,027
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively. Submitted Solution: ``` import sys N, M, Q = tuple(map(int, input().split())) S = input() T = input() def FindT1(S, T, M, i, j): A = S[i-1:j] ans = 0 for k in range(j-i+2-M): if A[k: k+M] == T: ans = ans + 1 return ans def FindT2(S, T, N, M): ans = [] for k in range(N-M +1): if S[k:k+M] == T: ans.append(1) else: ans.append(0) return ans if Q <= 20: for t in range(Q): i,j = tuple(map(int, sys.stdin.readline().split())) print(FindT1(S, T, M, i, j)) else: ans = FindT2(S, T, N, M) print(ans) for t in range(Q): i,j = tuple(map(int, sys.stdin.readline().split())) if j-i+1 < M: print("hey") else: print(sum(ans[i-1:j+1-M])) ``` No
5,028
Provide tags and a correct Python 3 solution for this coding contest problem. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Tags: dfs and similar, dsu, graphs Correct Solution: ``` N, M = map(int, input().split()) g = [[] for i in range(N)] for i in range(M): a, b = map(int, input().split()) g[a-1].append(b-1) g[b-1].append(a-1) visited = [0] * N def dfs(n): global visn visited[n] = 1 for i in g[n]: if not visited[i]: dfs(i) if N != M: print("NO") exit() dfs(0) if 0 in visited: print("NO") else: print("FHTAGN!") ```
5,029
Provide tags and a correct Python 3 solution for this coding contest problem. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Tags: dfs and similar, dsu, graphs Correct Solution: ``` n, m = [int(i) for i in input().split()] c = [int(i) for i in range(n+1)] def find (u): if u == c[u]: return u c[u] = find(c[u]) return c[u] ciclos = 0 for i in range(m): x, y = [int(j) for j in input().split()] x = find(x) y = find(y) if find(x) != find(y): c[x] = c[y] = max(x, y) else: ciclos += 1 conexo = True componente = find(1) for i in range(2, n+1, 1): if find(i) != componente: conexo = False if conexo and ciclos == 1: print('FHTAGN!') else: print('NO') exit(0) ```
5,030
Provide tags and a correct Python 3 solution for this coding contest problem. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Tags: dfs and similar, dsu, graphs Correct Solution: ``` inp = input().split() n = int(inp[0]) m = int(inp[1]) def dfs(x): f.add(x) for y in e[x]: if not y in f: dfs(y) if n >= 3 and n == m: e, f = [[] for i in range(n + 1)], set() for j in range(m): x, y = map(int, input().split()) e[x].append(y) e[y].append(x) dfs(1) print('FHTAGN!' if len(f) == n else 'NO') else: print('NO') ```
5,031
Provide tags and a correct Python 3 solution for this coding contest problem. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Tags: dfs and similar, dsu, graphs Correct Solution: ``` class Graph(): def __init__(self, number_nodes): self.nodes = [0] * (number_nodes+1) for i in range(number_nodes): self.nodes[i+1] = Node(i+1) def connect(self, node_1, node_2): self.find(node_1).neighbors.append(self.find(node_2)) self.find(node_2).neighbors.append(self.find(node_1)) def find(self, i): return self.nodes[i] def bfs(self): stack = [] stack.append(self.nodes[1]) visited = {} fhtagn = False while(stack): current = stack.pop() if current.value in visited: continue visited[current.value] = 1 for neighbor in current.neighbors: if neighbor.value not in visited: neighbor.known_by = current stack.append(neighbor) else: if current.known_by != neighbor: if fhtagn==False: fhtagn = True else: return("NO") if fhtagn == True and len(visited)+1 == len(self.nodes): return("FHTAGN!") return("NO") class Node(): def __init__(self, value): self.value = value self.neighbors = [] self.known_by = self vertices, edges = [int(s) for s in input().split()] graph = Graph(vertices) for i in range(edges): node_1, node_2 = [int(s) for s in input().split()] graph.connect(node_1, node_2) print(graph.bfs()) ```
5,032
Provide tags and a correct Python 3 solution for this coding contest problem. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Tags: dfs and similar, dsu, graphs Correct Solution: ``` lectura=lambda:map(int, input().split()) nVertices, nEdges= lectura() array1= [[] for i in range(nVertices + 1)] array2=[] for i in range(0, nEdges): x, y= lectura() array1[x].append(y) array1[y].append(x) def DFS(x): array2.append(x) for y in array1[x]: if (y not in array2): DFS(y) DFS(1) if(nVertices!=nEdges): conclusion="NO" else: if(len(array2)==nVertices): conclusion="FHTAGN!" else: conclusion="NO" print(conclusion) ```
5,033
Provide tags and a correct Python 3 solution for this coding contest problem. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Tags: dfs and similar, dsu, graphs Correct Solution: ``` # Problem from Codeforces # http://codeforces.com/problemset/problem/103/B parent = dict() ranks = dict() def make_set(N): global parent, ranks parent = [i for i in range(N + 5)] ranks = [0 for i in range(N + 5)] def find_set(u): if parent[u] != u: parent[u] = find_set(parent[u]) return parent[u] def union_set(u, v): up = find_set(u) vp = find_set(v) if up == vp: return if ranks[up] > ranks[vp]: parent[vp] = up elif ranks[up] < ranks[vp]: parent[up] = vp else: parent[up] = vp ranks[vp] += 1 def solution(): m, n = map(int, input().split()) if m != n: print('NO') return make_set(m) for i in range(m): a, b = map(int, input().split()) union_set(a, b) top_parent = find_set(1) for i in range(2, m): if find_set(i) != top_parent: print('NO') return print('FHTAGN!') solution() ```
5,034
Provide tags and a correct Python 3 solution for this coding contest problem. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Tags: dfs and similar, dsu, graphs Correct Solution: ``` n, m = map(int, input().split()) if n < 3 or n != m: # minimo 3 vertices para un circulo print("NO") # todo vertice debe tener un edge else: V = [] S = [] for i in range(n+1): #Armado de lista para conexiones de vertices V.append([]) for j in range(m): x, y = map(int, input().split()) V[x].append(y) #conexion de x con y V[y].append(x) #conexion de y con x def DFS(a): S.append(a) for v in V[a]: if not v in S: DFS(v) DFS(1) #hay que comenzar en algun punto if len(S) == n: print("FHTAGN!") else: print("NO") ```
5,035
Provide tags and a correct Python 3 solution for this coding contest problem. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Tags: dfs and similar, dsu, graphs Correct Solution: ``` def dfs(u): vis[u]=1 for v in adj[u]: if vis[v]==0: dfs(v) n,m=map(int,input().split()) vis=[0]*n adj=[[] for w in range(n)] for i in range (m): u,v = map(int,input().split()) u-=1 v-=1 adj[u].append(v) adj[v].append(u) cnt=0 for i in range(0,n-1): if vis[i]==0: dfs(i) cnt+=1 if cnt==1 and n==m: print('FHTAGN!') else: print('NO') ```
5,036
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Submitted Solution: ``` n, m = map(int, input().split()) if n < 3 or n != m: # minimo 3 vertices para un circulo print("NO") else: V = [] S = [] for i in range(n+1): #Armado de lista para conexiones de vertices V.append([]) for j in range(m): x, y = map(int, input().split()) V[x].append(y) #conexion de x con y V[y].append(x) #conexion de y con x def DFS(a): S.append(a) for v in V[a]: if not v in S: DFS(v) DFS(1) #hay que comenzar en algun punto if len(S) == n: print("FHTAGN!") else: print("NO") ``` Yes
5,037
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Submitted Solution: ``` def dfs(graph, start): visited[start] = True for i in graph[start]: if not visited[i]: dfs(graph, i) a, b = list(map(int, input().split(' '))) g = {} for i in range(1, a+1): g[i] = [] for i in range(b): x, y = map(int, input().split(' ')) g[x].append(y) g[y].append(x) visited = [True] + [False] * a dfs(g, 1) if False in visited: print("NO") quit() if a != b: print("NO") quit() print("FHTAGN!") ``` Yes
5,038
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Submitted Solution: ``` #Cthulhu n , m = map(int,input().split()) lst = [[] for i in range(n +1)] for i in range(m): x , y = map(int, input().split()) lst[x].append(y) lst[y].append(x) #print(lst) a = [0]*(n+1) b = [0]*(n+1) c = 0 def func(n): global a, b, c, lst a[n] = 1 for j in lst[n]: if a[j] == 1 and b[n] != j: c += 1 if(not a[j]): b[j] = n func(j) a[n] = 2 func(1) if c -1 or 0 in a[1: ]: print("NO") else: print("FHTAGN!") ``` Yes
5,039
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Submitted Solution: ``` n, m = [int(i) for i in input().split()] g = [[] for i in range(n)] mark = [False] * n if n is not m: print("NO") else: def dfs(node): mark[node] = True for u in g[node]: if mark[u] is False: dfs(u) for i in range(m): v, u = [int(x)-1 for x in input().split()] g[v].append(u) g[u].append(v) dfs(0) ans = True for i in range(1, n): if mark[i] is False: ans = False if ans is True: print("FHTAGN!") else: print("NO") ``` Yes
5,040
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Submitted Solution: ``` def dfs(visited,adj,ind,parent): if(visited[ind]==1): return [-1,-1] visited[ind]=1 for i in adj[ind]: if(visited[i]==0): parent[i]=ind x=dfs(visited,adj,i,parent) if(x[0]!=-1): return x elif(visited[i]==1 and i!=parent[ind]): return [i,ind] return [-1,-1] def dfsx(visited,adj,ind,parent,part): if(visited[ind]==1): return 0 visited[ind]=1 for i in adj[ind]: if(part[i]==1): continue if(visited[i]==0): parent[i]=ind x=dfs(visited,adj,i,parent) if(x!=0): return 1 elif(visited[i]==1 and i!=parent[ind] and part[i]==0): return 1 return 0 n,m=[int(i) for i in input().split()] l=[] adj=[[] for i in range(n)] part_cycle=[0 for i in range(n)] for i in range(m): a,b=[int(x) for x in input().split()] adj[a-1].append(b-1) adj[b-1].append(a-1) parent=[-1 for i in range(n)] visited=[0 for i in range(n)] x=dfs(visited,adj,0,parent) if(x[0]==-1): print("NO") else: part_cycle[x[0]]=1; part_cycle[x[1]]= 1; cycle=[] ind=x[1] cycle.append(x[0]) while(ind!=x[0]): cycle.append(ind) part_cycle[ind]=1; part_cycle[parent[ind]]=1; ind=parent[ind] flag=0 for i in cycle: x=dfsx(visited, adj, i, parent,part_cycle) if(x==1): print("NO") flag=1 break if(flag==0): print("FHTAGN!") ``` No
5,041
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Submitted Solution: ``` #!/usr/bin/python3 # B - Cthulhu import sys def dfs(curvertex): visited.add(curvertex) if curvertex in adjlist: for v in adjlist[curvertex]: if v not in visited: dfs(v) n, m = [int(x) for x in input().split()] if n != m: print("NO") sys.exit() adjlist = {} visited = set() for i in range(m): x, y = [int(x) for x in input().split()] if x not in adjlist: adjlist[x] = [y] else: adjlist[x].append(y) if y not in adjlist: adjlist[y] = [x] else: adjlist[y].append(x) dfs(next(iter(adjlist.keys()))) if visited == set(adjlist.keys()): print("FHTAGN!") else: print ("NO") ``` No
5,042
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Submitted Solution: ``` read = lambda: map(int, input().split()) n, m = read() graph = [set() for _ in range(n + 1)] for __ in range(m): u, v = read() graph[u].add(v) graph[v].add(u) def find_cycle(start): parents, stack = [0] * (n + 1), [(start, +1)] while stack: vertex, parent = stack.pop() parents[vertex] = parent for neighbour in graph[vertex]: if neighbour != parent: if parents[neighbour]: cycle = set() cycle.add(neighbour) while vertex <= neighbour: cycle.add(vertex) vertex = parents[vertex] return cycle stack.append((neighbour, vertex)) return set() cyc = find_cycle(1) if not cyc: print('NO') exit() def dfs(): visited = set(cyc) for start in cyc: stack = [(v, start) for v in graph[start] if v not in cyc] while stack: vertex, parent = stack.pop() visited.add(vertex) for neighbour in graph[vertex]: if neighbour != parent: if neighbour in visited: return set() stack.append((neighbour, vertex)) return visited print('FHTAGN!' if len(dfs()) == n else 'NO') ``` No
5,043
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. <image> Input The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ <image>). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Examples Input 6 6 6 3 6 4 5 1 2 5 1 4 5 4 Output FHTAGN! Input 6 5 5 6 4 6 3 1 5 1 1 2 Output NO Note Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1. A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0). A rooted tree is a tree where one vertex is selected to be the root. Submitted Solution: ``` """ https://codeforces.com/problemset/problem/103/B """ parent = [] ranks = [] edge = [] isCthulhu = False def makeSet(n): global parent, ranks parent = [i for i in range(n)] ranks = [0 for _ in range(n)] def findSet(u): global parent if parent[u] != u: parent[u] = findSet(parent[u]) return parent[u] def unionSet(u, v): global parent, ranks, isCthulhu up = findSet(u) vp = findSet(v) if up == vp: isCthulhu = True if ranks[up] > ranks[vp]: parent[vp] = up elif ranks[up] < ranks[vp]: parent[up] = vp else: ranks[up] += 1 parent[vp] = up def Kruskal(): for i in range(len(edge)): u = edge[i][0] v = edge[i][1] if u != v: unionSet(u, v) def main(): n, m = map(int, input().split()) makeSet(n + 1) for _ in range(m): edge.append(list(map(int, input().split()))) Kruskal() if isCthulhu: print('FHTAGN!') else: print('NO') if __name__ == "__main__": main() ``` No
5,044
Provide tags and a correct Python 3 solution for this coding contest problem. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Tags: greedy, implementation, math Correct Solution: ``` n,q = list(map(int, input().split())) a = input() Q = [] for _ in range(q): Q.append(list(map(int, input().split()))) d = [0] ab = 0 for i in a: if i == '1': ab += 1 d.append(ab) mod = int(1e9 + 7) p = [1] i = 1 for _ in range(n): i = (i*2)%mod p.append(i) for l,r in Q: y = r-l + 1 x = d[r] - d[l-1] y -= x print(((p[x]-1)*p[y])%mod) ```
5,045
Provide tags and a correct Python 3 solution for this coding contest problem. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Tags: greedy, implementation, math Correct Solution: ``` import sys r = sys.stdin.readlines() M = 10 ** 9 + 7 n, q = map(int, r[0].strip().split()) s = list(map(int, r[1].strip())) p = [0] for i in range(n): p.append(p[i] + int(s[i])) ans = [] for k in range(q): a, b = map(int, r[k + 2].strip().split()) l = b - a + 1 one = p[b] - p[a - 1] zero = l - one ans.append(str(((pow(2, one, M) - 1) * pow(2, zero, M)) % M)) sys.stdout.write("\n".join(ans)) ```
5,046
Provide tags and a correct Python 3 solution for this coding contest problem. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Tags: greedy, implementation, math Correct Solution: ``` #Wolve from sys import * m = 1000000007 n, q = map(int, stdin.readline().split()) a = stdin.readline() ans = [] t = [] count = 0 for i in a: if i == '1': count+=1 t.append(count) for _ in range(q): x,y=map(int,input().split()) if(x==1): p=t[y-1] else: p=t[y-1]-t[x-2] q=(y-x+1-p) s=pow(2,p+q,m)%m s=(((s%m)-(pow(2,q,m)%m))%m) ans.append(s) stdout.write('\n'.join(map(str, ans))) ```
5,047
Provide tags and a correct Python 3 solution for this coding contest problem. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Tags: greedy, implementation, math Correct Solution: ``` n,q = map(int,input().split()) a = input() sums = [] degrees = [1,2] res = [] d = 2 if (a[0] == "1"): s = 1 else: s = 0 sums.append(s) for i in range(1,n): if (a[i] == "1"): s += 1 d = (d*2)%1000000007 sums.append(s) degrees.append(d) for i in range(0,q): l,r = map(int,input().split()) k0 = (r - sums[r-1]) - (l - sums[l-1]) k1 = sums[r-1] - sums[l-1] if (a[l-1] == "0"): k0 += 1 else: k1 += 1 R = (degrees[k0]*(degrees[k1]-1))%1000000007 res.append(R) for i in range(0,q): print(res[i]) ```
5,048
Provide tags and a correct Python 3 solution for this coding contest problem. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Tags: greedy, implementation, math Correct Solution: ``` from sys import stdin, stdout n,q = tuple(map(int,stdin.readline().split())) arr = list(str(stdin.readline()))[:-1] arr[0] = int(arr[0]) for i in range(1,n): arr[i] = int(arr[i]) + arr[i-1] arr.insert(0,0) mod = int(1e9+7) inputs = [ tuple(map(int,line.split())) for line in stdin ] ans = [] for l,r in inputs: o = (arr[r] - arr[l-1]) z = (r - l + 1 - o) e_o = (pow(2,o,mod) - 1)%mod e_z = e_o * (pow(2,z,mod)-1)%mod ans.append(str(int((e_o + e_z)%mod))) stdout.write("\n".join(ans)) ```
5,049
Provide tags and a correct Python 3 solution for this coding contest problem. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Tags: greedy, implementation, math Correct Solution: ``` import sys MOD = 10 ** 9 + 7 r = sys.stdin.readlines() n, q = r[0].split(' ') n = int(n) q = int(q) s = r[1] c = [0] * (n + 1) for i in range(n): c[i + 1] = c[i] + (s[i] == '1') p2 = [1] * (2 * n + 1) for i in range(1, 2 * n + 1): p2[i] = p2[i - 1] * 2 % MOD out = [] for qq in range(q): a, b = r[qq + 2].split(' ') a = int(a) b = int(b) o = c[b] - c[a - 1] z = (b - a + 1) - o ans = (p2[o + z] - p2[z]) % MOD out.append(str(ans)) sys.stdout.write("\n".join(out)) ```
5,050
Provide tags and a correct Python 3 solution for this coding contest problem. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Tags: greedy, implementation, math Correct Solution: ``` import sys import math input=sys.stdin.readline def power(x, y, p) : res = 1 # Initialize result # Update x if it is more # than or equal to p x = x % p while (y > 0) : # If y is odd, multiply # x with result if ((y & 1) == 1) : res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res modi=1000000007 ones=[0]*(100001) for i in range(1,100001): ones[i]=(2*ones[i-1]+1)%modi zeroes=[1]*(100001) for i in range(1,100001): zeroes[i]=(2*zeroes[i-1])%modi n,q=map(int,input().split()) s=input() cones=[0]*(n+1) for i in range(1,n+1): if(s[i-1]=='1'): cones[i]=cones[i-1]+1 else: cones[i]=cones[i-1] for i in range(q): l,r=map(int,input().split()) curr=cones[r]-cones[l-1] ans=(ones[curr])%modi ans=((ans%modi)*(zeroes[r-l+1-curr]%modi))%modi print(ans) ```
5,051
Provide tags and a correct Python 3 solution for this coding contest problem. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Tags: greedy, implementation, math Correct Solution: ``` from sys import * m = 1000000007 n, q = map(int, stdin.readline().split()) a = stdin.readline() ans = [] t = [] count = 0 for i in a: if i == '1': count+=1 t.append(count) for _ in range(q): x,y=map(int,input().split()) if(x==1): p=t[y-1] else: p=t[y-1]-t[x-2] q=(y-x+1-p) s=pow(2,p+q,m) - (pow(2,q,m)) ans.append(s%m) stdout.write('\n'.join(map(str, ans))) ```
5,052
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Submitted Solution: ``` from sys import stdin,stdout n,q=map(int,input().split()) mod=1000000007 o=[] s=[] r=m=0 a=input() for i in a: if i=='0': r+=1 else: m+=1 o.append(r) s.append(m) z=[1] #print(o) for i in range(100000): z.append((z[-1]*2)%mod) for j in range(q): l,r=(int(j) for j in stdin.readline().split()) m=r-l+1 zs=o[r-1]-o[l-1]+(a[l-1]=='0') os=m-zs #print(zs,os) if zs!=0: print((((z[os]-1)%mod)*((z[zs])%mod))%mod) else: print(((z[os]-1)%mod)) ``` Yes
5,053
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Submitted Solution: ``` import sys input = sys.stdin.readline n, q = map(int, input().split()) s = input() pref = [0 for i in range(n + 1)] for i in range(1, n + 1): pref[i] = pref[i - 1] + (s[i - 1] == '1') mod = 1000000007 ans = [] for i in range(q): a, b = map(int, input().split()) k = pref[b] - pref[a - 1]; N = b - a + 1 z = N - k ans.append((pow(2, k, mod) - 1) * pow(2, z, mod) % mod) print(*ans) ``` Yes
5,054
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Submitted Solution: ``` import sys r = sys.stdin.readlines() n, q = r[0].split(' ') n = int(n) q = int(q) M = 10 ** 9 + 7 twopow = [1] * (2 * n + 1) for j in range(1, (2 * n + 1)): twopow[j] = twopow[j - 1] * 2 % M s = r[1] p = [0] * (n + 1) for v in range(n): p[v + 1] = p[v] + (s[v] == '1') ans = [0] * q for k in range(q): a, b = r[k + 2].split(' ') a = int(a) b = int(b) l = b - a + 1 one = p[b] - p[a - 1] v = (twopow[l] - twopow[l - one] + M) % M ans[k] = str(v) sys.stdout.write("\n".join(ans)) ``` Yes
5,055
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Submitted Solution: ``` import sys r = sys.stdin.readlines() M = 10 ** 9 + 7 n, q = r[0].strip().split() n = int(n) q = int(q) s = r[1] p = [0] k = 0 for v in range(n): d = int(s[v]) k += d p.append(k) ans = [] for k in range(q): a, b = r[k + 2].strip().split() a = int(a) b = int(b) l = b - a + 1 one = p[b] - p[a - 1] ans.append((pow(2, l, M) - pow(2, l - one, M) + M) % M) sys.stdout.write("\n".join(map(str, ans))) ``` Yes
5,056
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Submitted Solution: ``` from collections import defaultdict, deque, Counter from sys import stdin, stdout from heapq import heappush, heappop import math import io import os import math import bisect #?############################################################ def gcd(a,b): if a == 0: return b return gcd(b % a, a) def lcm(a,b): return (a // gcd(a,b))* b def isPrime(x): for i in range(2, x): if i*i > x: break if (x % i == 0): return False return True #?############################################################ 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 #?############################################################ def primeFactors(n): l = [] while n % 2 == 0: l.append(2) n = n / 2 for i in range(3, int(math.sqrt(n))+1, 2): while n % i == 0: l.append(int(i)) n = n / i if n > 2: l.append(n) return list(set(l)) #?############################################################ def power(x, y, p): res = 1 x = x % p if (x == 0): return 0 while (y > 0): if ((y & 1) == 1): res = (res * x) % p y = y >> 1 x = (x * x) % p return res #?############################################################ def sieve(n): prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 return prime #?############################################################ def digits(n): c = 0 while (n > 0): n //= 10 c += 1 return c #?############################################################ def ceil(n, x): if (n % x == 0): return n//x return n//x+1 #?############################################################ def mapin(): return map(int, input().split()) #?############################################################ # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # python3 15.py<i:n>op n, q = map(int, input().split()) s = input() nn = 1000000009 N = 1000003 l = [0]*N ll = [0]*(len(s)+1) tt = 0 for i in range(len(s)): if(s[i] == '0'): tt+=1 ll[i+1] = tt temp = 1 for i in range(N): l[i] = temp%nn temp = temp+temp temp = temp%nn # print(l[0:116]) # print(ll)/ for i in range(q): a, b = map(int, input().split()) d = ll[b] - ll[a-1] c = b-a+1-d e = l[c]-1 f = l[d] print((e*f)%nn) ``` No
5,057
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Sat Jun 8 11:24:26 2019 @author: plosi """ import math def compute(l,r,B): if l==0: n=B[r] else: n=B[r]-B[l-1] j=r-(l-1)-n return (math.pow(2,n)-1)*math.pow(2,j) def main(): n,q=input().split(" ") n=int(n) q=int(q) arr=input() narr=[0 for i in range(n)] for i in range(n): narr[i]=int(arr[i]) B=[0 for i in range(n)] B[0]=narr[0] for i in range(1,len(arr)): B[i]=B[i-1]+narr[i] for i in range(q): l,r=input().split(" ") l=int(l)-1 r=int(r)-1 print(compute(l,r,B)) main() ``` No
5,058
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Submitted Solution: ``` n,q = map(int,input().split()) a = input() sums = [] degrees = [1,2] res = [] d = 2 if (a[0] == "1"): s = 1 else: s = 0 sums.append(s) for i in range(1,n): if (a[i] == "1"): s += 1 d = d%1000000007*2 sums.append(s) degrees.append(d) for i in range(0,q): l,r = map(int,input().split()) k0 = (r - sums[r-1]) - (l - sums[l-1]) k1 = sums[r-1] - sums[l-1] if (a[l-1] == "0"): k0 += 1 else: k1 += 1 R = degrees[k0]*(degrees[k1]-1) res.append(R) for i in range(0,q): print(res[i]) ``` No
5,059
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i ∈ \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0. For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \\_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\\_, \\_, 2]. After eating the last part, JATC's enjoyment will become 4. However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order. All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. Input The first line contains two integers n and q (1 ≤ n, q ≤ 100 000). The second line contains a string of n characters, each character is either '0' or '1'. The i-th character defines the deliciousness of the i-th part. Each of the following q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of the corresponding query. Output Print q lines, where i-th of them contains a single integer — the answer to the i-th query modulo 10^9 + 7. Examples Input 4 2 1011 1 4 3 4 Output 14 3 Input 3 2 111 1 2 3 3 Output 3 1 Note In the first example: * For query 1: One of the best ways for JATC to eats those parts is in this order: 1, 4, 3, 2. * For query 2: Both 3, 4 and 4, 3 ordering give the same answer. In the second example, any order of eating parts leads to the same answer. Submitted Solution: ``` mod=1000000007 n,m=map(int,input().split()) s=list(input()) l=[0]*(n+1) for i in range(1,n+1): l[i]=l[i-1]+int(s[i-1]) print(l) for i in range(m): l1,r=map(int,input().split()) s=r-l1 no=l[r]-l[l1-1] ans=pow(2,s+1,mod)-pow(2,s-no+1,mod) print(ans) ``` No
5,060
Provide tags and a correct Python 3 solution for this coding contest problem. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Tags: greedy, implementation Correct Solution: ``` n,s=input().split() n=int(n) s=int(s) l=input().split() l=list(map(int,l)) x=sum(l) m=min(l) h=len(l) if x<s: print(-1) elif m*h<=(x-s): print(m) else: q=(m*h-(x-s))/h if int(q)==q: print(m-int(q)) else: print(m-(int(q)+1)) ```
5,061
Provide tags and a correct Python 3 solution for this coding contest problem. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Tags: greedy, implementation Correct Solution: ``` ss = 0 n, s = map(int, input().split()) v = list(map(int, input().split())) m,ss = min(v), sum(v) if ss < s: print(-1) else: print(min(m, (ss-s)//n)) ```
5,062
Provide tags and a correct Python 3 solution for this coding contest problem. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Tags: greedy, implementation Correct Solution: ``` n, s = map(int, input().split()) allCups = list(map(int, input().split())) sumK = sum(allCups) minK = min(allCups) if sumK < s: print(-1) else: if sumK - (minK * n) >= s: print(minK) else: s = s - (sumK - (minK * n)) #print(s) if s % n == 0: print(minK - (s // n)) else: print(minK - (s // n) - 1) ```
5,063
Provide tags and a correct Python 3 solution for this coding contest problem. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Tags: greedy, implementation Correct Solution: ``` n, m = map(int, input().strip().split()) kegs = list(map(int, input().strip().split())) import math if sum(kegs) < m : print(-1) else : import operator index, value = min(enumerate(kegs), key=operator.itemgetter(1)) res = m for i, k in enumerate(kegs): if i != index: res -= k-value if res <= 0: print(value) else: print(value-(math.ceil(res/n))) ```
5,064
Provide tags and a correct Python 3 solution for this coding contest problem. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Tags: greedy, implementation Correct Solution: ``` import math def main(): n,s = map(int,input().split()) volume = list(map(int,input().split())) if s > sum(volume): print(-1) return min_val = min(volume) for i in range(n): diff = volume[i]-min_val if s >= diff: volume[i] = min_val s -= diff else: volume[i] -= s s = 0 if s == 0: break if s > 0: remove1 = s//n remove2 = s%n #print(remove1,remove2) print(min_val-remove1-math.ceil(remove2/n)) else: print(min_val) main() ```
5,065
Provide tags and a correct Python 3 solution for this coding contest problem. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Tags: greedy, implementation Correct Solution: ``` import sys a, b = input().split() a, b = int(a), int(b) k = input().split() kk = k[:] k = [] sum = 0 for i in kk: a = int(i) sum += a k.append(a) if sum < b: print(-1) sys.exit() k.sort() least = k[0] summ = sum - least * len(k) k = [least for i in k] if(summ >= b): print(least) sys.exit() else: b -= summ least -= (b // len(k)) + (1 if b % len(k) > 0 else 0) print(least) ```
5,066
Provide tags and a correct Python 3 solution for this coding contest problem. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Tags: greedy, implementation Correct Solution: ``` def main(): n, s = map(int, input().split()) v = list(map(int, input().split())) minn = min(v) summ = 0 alll = 0 for el in v: alll += el if alll < s: print(-1) return for i in range(n): summ += v[i] - minn s -= summ if s < 0: print(minn) return else: k = s // n if s % n > 0: k += 1 print(minn - k) return main() ```
5,067
Provide tags and a correct Python 3 solution for this coding contest problem. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Tags: greedy, implementation Correct Solution: ``` n,s=map(int,input().split()) a=[int(i) for i in input().split()] mini=min(a) t=0 for i in range(n): t=t+a[i]-mini if(t>=s): print(mini) elif(s>sum(a)): print("-1") else: rem=s-t if(rem//n==rem/n): k=rem//n print(mini-k) else: k=rem//n+1 print(mini-k) ```
5,068
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Submitted Solution: ``` import math m,n=map(int,input().split()) li=sorted(list(map(int,input().split()))) l=li[0] bli=[] if sum(li)<n: print(-1) exit() for i in range(len(li)): bli.append(li[i]-li[0]) if sum(bli)>=n: print(l) else: print(l-math.ceil((n-sum(bli))/m)) ``` Yes
5,069
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Submitted Solution: ``` # *********************************************** # # achie27 # # *********************************************** def retarray(): return list(map(int, input().split())) import math n, s = retarray() a = retarray() min_keg = min(a) acc = 0 for x in a: acc += (x - min_keg) if acc >= s: print(min_keg) else: x = math.ceil((s-acc)/n) if x > min_keg: print(-1) else: print(min_keg-x) ``` Yes
5,070
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Submitted Solution: ``` import math n, s = map(int, input().split()) kegs = [int(k) for k in input().split()] if s > sum(kegs): print(-1) exit() opsleft = s minimum = min(kegs) amtleft = 0 for keg in kegs: amtleft += keg-minimum if s <= amtleft: print(minimum) else: res = minimum - math.ceil((s - amtleft) / n) print(res) ``` Yes
5,071
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Submitted Solution: ``` a,b=map(int,input().split()) z=list(map(int,input().split())) s=sum(z);r=min(z) if b>s:print(-1) else:print(min(r,(s-b)//a)) ``` Yes
5,072
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Submitted Solution: ``` n, s = map(int, input().split()) v = list(map(int, input().split())) least = min(v) if sum(v) < s: print(-1) else: for i in v: s -= (i-least) if s != 0: least -= (s)/n print(int(least)) ``` No
5,073
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Submitted Solution: ``` n, s = list(map(int, input().split())) a= list(map(int, input().split())) if s > sum(a): print(-1) elif s == sum(a): print(0) else: a = sorted(a) total = sum(a) b = [0 for _ in range(len(a))] b[0] = a[0] for i in range(1, len(a)): b[i] = a[i] + b[i-1] c = [0 for _ in range(len(a))] c[0] = total - a[0] * (len(a)) for i in range(1, len(a)): c[i] = total - b[i] - a[i] * (len(a)-i-1) if s <= c[0]: print(a[0]) else: s -= c[0] add = s // a[0] + bool(s%a[0]) final = a[0] - add print(final) ``` No
5,074
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Submitted Solution: ``` ''' Thruth can only be found at one place - THE CODE ''' ''' Copyright 2018, SATYAM KUMAR''' from sys import stdin, stdout import cProfile, math from collections import Counter from bisect import bisect_left,bisect,bisect_right import itertools from copy import deepcopy from fractions import Fraction import sys, threading sys.setrecursionlimit(10**6) # max depth of recursion threading.stack_size(2**27) # new thread will get stack of such size printHeap = str() memory_constrained = False P = 10**9+7 import sys sys.setrecursionlimit(10000000) class Operation: def __init__(self, name, function, function_on_equal, neutral_value=0): self.name = name self.f = function self.f_on_equal = function_on_equal def add_multiple(x, count): return x * count def min_multiple(x, count): return x def max_multiple(x, count): return x sum_operation = Operation("sum", sum, add_multiple, 0) min_operation = Operation("min", min, min_multiple, 1e9) max_operation = Operation("max", max, max_multiple, -1e9) class SegmentTree: def __init__(self, array, operations=[sum_operation, min_operation, max_operation]): self.array = array if type(operations) != list: raise TypeError("operations must be a list") self.operations = {} for op in operations: self.operations[op.name] = op self.root = SegmentTreeNode(0, len(array) - 1, self) def query(self, start, end, operation_name): if self.operations.get(operation_name) == None: raise Exception("This operation is not available") return self.root._query(start, end, self.operations[operation_name]) def summary(self): return self.root.values def update(self, position, value): self.root._update(position, value) def update_range(self, start, end, value): self.root._update_range(start, end, value) def __repr__(self): return self.root.__repr__() class SegmentTreeNode: def __init__(self, start, end, segment_tree): self.range = (start, end) self.parent_tree = segment_tree self.range_value = None self.values = {} self.left = None self.right = None if start == end: self._sync() return self.left = SegmentTreeNode(start, start + (end - start) // 2, segment_tree) self.right = SegmentTreeNode(start + (end - start) // 2 + 1, end, segment_tree) self._sync() def _query(self, start, end, operation): if end < self.range[0] or start > self.range[1]: return None if start <= self.range[0] and self.range[1] <= end: return self.values[operation.name] self._push() left_res = self.left._query(start, end, operation) if self.left else None right_res = self.right._query(start, end, operation) if self.right else None if left_res is None: return right_res if right_res is None: return left_res return operation.f([left_res, right_res]) def _update(self, position, value): if position < self.range[0] or position > self.range[1]: return if position == self.range[0] and self.range[1] == position: self.parent_tree.array[position] = value self._sync() return self._push() self.left._update(position, value) self.right._update(position, value) self._sync() def _update_range(self, start, end, value): if end < self.range[0] or start > self.range[1]: return if start <= self.range[0] and self.range[1] <= end: self.range_value = value self._sync() return self._push() self.left._update_range(start, end, value) self.right._update_range(start, end, value) self._sync() def _sync(self): if self.range[0] == self.range[1]: for op in self.parent_tree.operations.values(): current_value = self.parent_tree.array[self.range[0]] if self.range_value is not None: current_value = self.range_value self.values[op.name] = op.f([current_value]) else: for op in self.parent_tree.operations.values(): result = op.f( [self.left.values[op.name], self.right.values[op.name]]) if self.range_value is not None: bound_length = self.range[1] - self.range[0] + 1 result = op.f_on_equal(self.range_value, bound_length) self.values[op.name] = result def _push(self): if self.range_value is None: return if self.left: self.left.range_value = self.range_value self.right.range_value = self.range_value self.left._sync() self.right._sync() self.range_value = None def __repr__(self): ans = "({}, {}): {}\n".format(self.range[0], self.range[1], self.values) if self.left: ans += self.left.__repr__() if self.right: ans += self.right.__repr__() return ans def display(string_to_print): stdout.write(str(string_to_print) + "\n") def primeFactors(n): #n**0.5 complex factors = dict() for i in range(2,math.ceil(math.sqrt(n))+1): while n % i== 0: if i in factors: factors[i]+=1 else: factors[i]=1 n = n // i if n>2: factors[n]=1 return (factors) def isprime(n): """Returns True if n is prime.""" if n < 4: return True if n % 2 == 0: return False if n % 3 == 0: return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w w = 6 - w return True def test_print(*args): if testingMode: print(args) def display_list(list1, sep=" "): stdout.write(sep.join(map(str, list1)) + "\n") def get_int(): return int(stdin.readline().strip()) def get_tuple(): return map(int, stdin.readline().split()) def get_list(): return list(map(int, stdin.readline().split())) memory = dict() def clear_cache(): global memory memory = dict() def cached_fn(fn, *args): global memory if args in memory: return memory[args] else: result = fn(*args) memory[args] = result return result # -------------------------------------------------------------- MAIN PROGRAM TestCases = False testingMode = False optimiseForReccursion = False #Can not be used clubbed with TestCases def comp(li): return len(li) def main(): n,k=get_tuple() li = get_list() sm = sum(li) res = 0 print((sm-k)//n) if sm-k>=0 else print(-1) # --------------------------------------------------------------------- END if TestCases: for _ in range(get_int()): cProfile.run('main()') if testingMode else main() else: (cProfile.run('main()') if testingMode else main()) if not optimiseForReccursion else threading.Thread(target=main).start() ``` No
5,075
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by s liters of kvass. Input The first line contains two integers n and s (1 ≤ n ≤ 10^3, 1 ≤ s ≤ 10^{12}) — the number of kegs and glass volume. The second line contains n integers v_1, v_2, …, v_n (1 ≤ v_i ≤ 10^9) — the volume of i-th keg. Output If the Fair Nut cannot pour his glass by s liters of kvass, print -1. Otherwise, print a single integer — how much kvass in the least keg can be. Examples Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 Note In the first example, the answer is 3, the Fair Nut can take 1 liter from the first keg and 2 liters from the third keg. There are 3 liters of kvass in each keg. In the second example, the answer is 2, the Fair Nut can take 3 liters from the first keg and 1 liter from the second keg. In the third example, the Fair Nut can't pour his cup by 7 liters, so the answer is -1. Submitted Solution: ``` if __name__ == "__main__": (n,s) = [ int(x) for x in input().split()] #print(n,m) val = [int(x) for x in input().split()] sum = 0 for x in val: sum+=x ans = int((sum-s)/n) if sum-s <0: ans = -1 print(ans) ``` No
5,076
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k — your skill in Cardbluff. Each judge has a number a_i — an indicator of uncertainty about your entrance to the professional layer and a number e_i — an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x ⋅ y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ 10^{12}) — the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≤ a_i ≤ 10^{12}) — the uncertainty of i-th judge The third line contains n integers in the same format (1 ≤ e_i ≤ 10^9), e_i — the experience of i-th judge. Output Print the single integer — minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1 Submitted Solution: ``` from sys import stdout def ask(x,y) : print('?',x,y) stdout.flush() return input() == 'x' def work() : if ask(0, 1) : return 1 l = 1 while ask(l*2,l) : l*=2 r = 2*1000000000 l += 1 while r > l : mid=(l+r)//2 if ask(mid, (mid+1)//2) : l=mid+1 else : r=mid return l while input()=='start' : print('!',work()) stdout.flush() ``` No
5,077
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k — your skill in Cardbluff. Each judge has a number a_i — an indicator of uncertainty about your entrance to the professional layer and a number e_i — an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x ⋅ y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ 10^{12}) — the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≤ a_i ≤ 10^{12}) — the uncertainty of i-th judge The third line contains n integers in the same format (1 ≤ e_i ≤ 10^9), e_i — the experience of i-th judge. Output Print the single integer — minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1 Submitted Solution: ``` import math n,k=map(int,input().split()) a=list(map(int,input().split())) e=list(map(int,input().split())) e.sort() big=a[0] for i in range(n-1): big=math.gcd(big,a[i+1]) if big==1: break if big==1: print(0) else: factors=[] for i in range(1,k+1): if big%i==0: factors.append(i) ind=len(factors)-1 nums=[] while True: if ind==0: break if big==1: break if big%factors[ind]==0: nums.append(factors[ind]) big//=factors[ind] else: ind-=1 if ind==0: print(-1) else: j=len(nums) if j>n: print(-1) else: print(j*sum(e[:j])) ``` No
5,078
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k — your skill in Cardbluff. Each judge has a number a_i — an indicator of uncertainty about your entrance to the professional layer and a number e_i — an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x ⋅ y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ 10^{12}) — the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≤ a_i ≤ 10^{12}) — the uncertainty of i-th judge The third line contains n integers in the same format (1 ≤ e_i ≤ 10^9), e_i — the experience of i-th judge. Output Print the single integer — minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1 Submitted Solution: ``` import math n,k=map(int,input().split()) a=list(map(int,input().split())) e=list(map(int,input().split())) e.sort() big=a[0] for i in range(n-1): big=math.gcd(big,a[i+1]) if big==1: break if big==1: print(0) else: factors=[] for i in range(1,k+1): if big%i==0: factors.append(i) ind=len(factors)-1 nums=[] while True: if ind==0: break if big==1: break if big%factors[ind]==0: nums.append(factors[ind]) big//=factors[ind] else: ind-=1 if ind==0: print(-1) else: j=len(nums) print(j*sum(e[:j])) ``` No
5,079
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Tags: dfs and similar, dp, dsu, graphs, greedy Correct Solution: ``` import sys import collections def main(): input = iter(sys.stdin) N, M = map(int, next(input).split()) dsu = DSU(N + M) edges = [] for i in range(N): line = next(input).strip() for j, sign in enumerate(line): j = j + N if sign == '=': dsu.merge(i, j) else: edges.append((i, j) if sign == '<' else (j, i)) incoming = collections.defaultdict(set) outgoing = collections.defaultdict(set) nodes = sorted(set([dsu.root(i) for i in range(N + M)])) for i, j in edges: incoming[dsu.root(i)].add(dsu.root(j)) outgoing[dsu.root(j)].add(dsu.root(i)) no_incoming = list(set(i for i in nodes if i not in incoming)) ordering = [] while no_incoming: node = no_incoming.pop(-1) ordering.append(node) for n in outgoing[node]: incoming[n].discard(node) if not incoming[n]: no_incoming.append(n) if len(ordering) != len(nodes): return 'NO' root_to_index = {} for n in reversed(ordering): if not outgoing[n]: root_to_index[n] = 0 else: root_to_index[n] = max(root_to_index[x] for x in outgoing[n]) + 1 s = ['YES'] s.append(' '.join(str(root_to_index[dsu.root(i)] + 1) for i in range(N))) s.append(' '.join(str(root_to_index[dsu.root(i + N)] + 1) for i in range(M))) return '\n'.join(s) class DSU(): def __init__(self, n): self.parents = [i for i in range(n)] def root(self, i): try: if self.parents[i] != i: self.parents[i] = self.root(self.parents[i]) except: print(i, len(self.parents)) raise return self.parents[i] def merge(self, i, j): r1 = self.root(i) r2 = self.root(j) if r1 != r2: self.parents[r1] = r2 if __name__ == '__main__': print(main()) ```
5,080
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Tags: dfs and similar, dp, dsu, graphs, greedy Correct Solution: ``` class UnionFind: def __init__(self, n): self.follow = [-1]*(n+1) self.num_follower = [1]*(n+1) def root_index_of(self, a): r = a while self.follow[r] > -1: r = self.follow[r] return r def connected(self, a, b): return self.root_index_of(a) == self.root_index_of(b) def connect(self, a, b): ra = self.root_index_of(a) rb = self.root_index_of(b) if ra == rb: return if self.num_follower[ra] < self.num_follower[rb]: self.follow[ra] = rb self.follow[a] = rb self.num_follower[rb] += self.num_follower[ra] else: self.follow[rb] = ra self.follow[b] = ra self.num_follower[ra] += self.num_follower[rb] import sys from collections import deque input = sys.stdin.readline n, m = map(int, input().split()) s = [input() for _ in range(n)] uf = UnionFind(n+m) v = [[] for _ in range(n+m)] c = [0]*(n+m) for i in range(n): for j in range(m): if s[i][j] == "=": uf.connect(i, j+n) for i in range(n): for j in range(m): if s[i][j] == "<": v[uf.root_index_of(i)].append(uf.root_index_of(n+j)) c[uf.root_index_of(n+j)] += 1 elif s[i][j] == ">": v[uf.root_index_of(n+j)].append(uf.root_index_of(i)) c[uf.root_index_of(i)] += 1 ans = [0]*(n+m) used = [0]*(n+m) que = deque([]) for i in range(n+m): if c[i] == 0: ans[i] = 1 used[i] = 1 que.append(i) while que: x = que.popleft() for i in v[x]: if used[i]: continue ans[i] = max(ans[x]+1, ans[i]) c[i] -= 1 if c[i] == 0: used[i] = 1 que.append(i) for i in range(n+m): if used[i] == 0: print("No") exit() for i in range(n): for j in range(m): if s[i][j] == "=": if ans[uf.root_index_of(i)] != ans[uf.root_index_of(n+j)]: print("No") exit() for i in range(n): for j in range(m): if s[i][j] == "<": if ans[uf.root_index_of(i)] >= ans[uf.root_index_of(n+j)]: print("No") exit() for i in range(n): for j in range(m): if s[i][j] == ">": if ans[uf.root_index_of(i)] <= ans[uf.root_index_of(n+j)]: print("No") exit() print("Yes") for i in range(n): print(ans[uf.root_index_of(i)], end=" ") print() for j in range(m): print(ans[uf.root_index_of(j+n)], end=" ") print() ```
5,081
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Tags: dfs and similar, dp, dsu, graphs, greedy Correct Solution: ``` import time debug = False n1, m2 = map(int, input().split()) tests = [] for i in range(n1): tests.append(list(input())) if debug: print (tests) begin = time.time() if debug: print("---") marks1 = [] result1 = [] for i in range(n1): marks1.append([i,0.0]) result1.append(0) marks2 = [] result2 = [] for j in range(m2): marks2.append([j,0.0]) result2.append(0) for i in range(n1): for j in range(m2): test = tests[i][j] if test == ">": marks1[i][1] += 1.0 elif test == "<": marks2[j][1] += 1.0 else: marks1[i][1] += 0.0001 marks2[j][1] += 0.0001 marks1.sort(key=lambda val: val[1]) marks2.sort(key=lambda val: val[1]) if debug: print(marks1) print(marks2) i = 0 j = 0 value = 0 lastmark = -1 lastItem = [0,0] while i < n1 or j < m2: LetAdd = 0 if i < n1 and j < m2: test = tests[marks1[i][0]][marks2[j][0]] if test == ">": LetAdd = 2 else: LetAdd = 1 elif i < n1: LetAdd = 1 else: LetAdd = 2 if LetAdd == 1: if marks1[i][1] != lastmark and lastItem[0] != 2 or lastItem[0] == 2 and tests[marks1[i][0]][lastItem[1]] != '=': if debug: if lastItem[0] == 2: print(1, lastmark, lastItem, marks1[i][0], tests[marks1[i][0]][lastItem[1]]) else: print(1, lastmark, lastItem, marks1[i][0]) value += 1 lastmark = marks1[i][1] result1[marks1[i][0]] = value lastItem = [1,marks1[i][0]] i += 1 else: if marks2[j][1] != lastmark and lastItem[0] != 1 or lastItem[0] == 1 and tests[lastItem[1]][marks2[j][0]] != '=': if debug: if lastItem[0] == 1: print(2, lastmark, lastItem, marks2[j][0], tests[lastItem[1]][marks2[j][0]]) else: print(2, lastmark, lastItem, marks2[j][0]) value += 1 lastmark = marks2[j][1] result2[marks2[j][0]] = value lastItem = [2,marks2[j][0]] j += 1 if debug: print("Set ", lastItem, " to ", value) CheckCorrect = True for i in range(n1): for j in range(m2): test = tests[i][j] if test == ">": if result1[i] <= result2[j]: CheckCorrect = False elif test == "<": if result1[i] >= result2[j]: CheckCorrect = False else: if result1[i] != result2[j]: CheckCorrect = False if debug: print("---") if debug: print("Time: ", time.time() - begin) if CheckCorrect: print ("Yes") else: print ("No") if CheckCorrect or debug: print (*result1) print (*result2) ```
5,082
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Tags: dfs and similar, dp, dsu, graphs, greedy Correct Solution: ``` def prov(mass, now): check = True for i in range(n): for k in range(m): if now[i][k] == '>' and mass[i] <= mass[n + k]: check = False break elif now[i][k] == '<' and mass[i] >= mass[n + k]: check = False break elif now[i][k] == '=' and mass[i] != mass[n + k]: check = False break if not check: break return check def prog(mass, n, m): prov = True for i in range(1, m): for k in range(n): if mass[i][k] < mass[i - 1][k]: prov = False break if not prov: break if not prov: return False else: mass_new = [] for i in range(1, m): mass_n = [] for k in range(n): mass_n.append(mass[i][k] - mass[i - 1][k]) mass_new.append(max(mass_n)) arr = [1 for i in range(m)] now = 1 if 1 in mass[0][:-1]: now += 1 arr = [2 for i in range(m)] for i in range(1, m): now += mass_new[i - 1] arr[mass[i][-1]] = now return arr n, m = map(int, input().split()) if n + m <= 6: now = [] for i in range(n): now.append(input()) ppp = True for i1 in range(n + m): for i2 in range(n + m): for i3 in range(n + m): for i4 in range(n + m): for i5 in range(n + m): for i6 in range(n + m): mass = [i1 + 1, i2 + 1, i3 + 1, i4 + 1, i5 + 1, i6 + 1][:n + m] if prov(mass, now) and ppp: print('Yes') print(*mass[:n]) print(*mass[n:]) ppp = False if ppp: print('No') else: mass = [[] for i in range(m)] mass1 = [[] for i in range(n)] for i in range(n): now = input() for k in range(m): if now[k] == '<': mass[k].append(1) mass1[i].append(-1) elif now[k] == '=': mass[k].append(0) mass1[i].append(0) else: mass[k].append(-1) mass1[i].append(1) for i in range(m): mass[i].append(i) for i in range(n): mass1[i].append(i) mass.sort() mass1.sort() arr = prog(mass, n, m) arr1 = prog(mass1, m, n) if arr == False or arr1 == False: print('No') else: print('Yes') print(*arr1) print(*arr) ```
5,083
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Tags: dfs and similar, dp, dsu, graphs, greedy Correct Solution: ``` n, m = (int(t) for t in input().split(' ')) def direction(c): if c == '=': return 0 if c == '>': return 1 return -1 mx = [[direction(c) for c in input()] for _ in range(n)] index = 0 class DSet(object): def __init__(self, value): global index self.values = set([value]) self.index = index index += 1 self.edges_to = set() self.edges_from = set() def __len__(self): return len(self.values) def update(self, other_dset): self.values.update(other_dset.values) def add_edge_to(self, i): self.edges_to.add(i) def add_edge_from(self, i): self.edges_from.add(i) def remove_edge_from(self, i): self.edges_from.remove(i) dsu = [DSet(i) for i in range(n+m)] def union(v1, v2): if len(dsu[v1]) > len(dsu[v2]): d = dsu[v1] d.update(dsu[v2]) else: d = dsu[v2] d.update(dsu[v1]) dsu[v1] = dsu[v2] = d for i in range(n): for j in range(m): if not mx[i][j]: union(i, n + j) for i in range(n): for j in range(m): if mx[i][j] > 0: dsu[i].add_edge_from(dsu[n + j].index) dsu[n+j].add_edge_to(dsu[i].index) elif mx[i][j] < 0: dsu[n + j].add_edge_from(dsu[i].index) dsu[i].add_edge_to(dsu[n+j].index) weights = [1] * (n+m) dsu_by_index = { d.index: d for d in dsu } while True: try: v = next(d for d in range(n+m) if not len(dsu[d].edges_from) and len(dsu[d].edges_to)) except: break dsuv = dsu[v] for edge in dsu[v].edges_to: dsue = dsu_by_index[edge] dsue.remove_edge_from(dsuv.index) for value in dsue.values: weights[value] = weights[v] + 1 dsu[v].edges_to.clear() ok = all(not len(d.edges_from) and not len(d.edges_to) for d in dsu) if ok: print('Yes') print(*weights[0:n]) print(*weights[n:]) else: print('No') ```
5,084
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Tags: dfs and similar, dp, dsu, graphs, greedy Correct Solution: ``` #!/usr/bin/env pypy import collections #import random import heapq import bisect import math import time class Solution2: def solve(self, A1, A2): pass def gcd(a, b): if not b: return a return gcd(b, a%b) def lcm(a, b): return b*a//gcd(b,a) class Solution: def solve(self, grid): def union(i,j): leader_i, leader_j = find(i), find(j) sets[leader_j] = sets[i] = sets[j] = leader_i def find(i): while i != sets[i]: i = sets[i] return i N = len(grid) + len(grid[0]) sets = list(range(N)) for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == '=': union(i,j+len(grid)) graph = collections.defaultdict(set) inc = collections.defaultdict(set) for i in range(len(grid)): for j in range(len(grid[0])): leader_i, leader_j = find(i), find(j+len(grid)) if grid[i][j] == '>': if leader_i == leader_j: print("No") return graph[leader_j].add(leader_i) inc[leader_i].add(leader_j) elif grid[i][j] == '<': if leader_i == leader_j: print("No") return graph[leader_i].add(leader_j) inc[leader_j].add(leader_i) self.levels = [0]*N def dfs(node, level): self.levels[node] = max(self.levels[node],level) if not inc[node]: seen.add(node) for next_node in graph[node]: inc[next_node].discard(node) dfs(next_node,self.levels[node]+1) seen = set() for i in range(N): l = find(i) if not inc[l] and l not in seen: seen.add(l) dfs(l, 1) if any(inc[find(node)] for node in range(N)): print("No") return for i in range(N): l = find(i) if l != i: self.levels[i] = self.levels[l] print("Yes") print(' '.join(str(o) for o in self.levels[:len(grid)])) print(' '.join(str(o) for o in self.levels[len(grid):])) sol = Solution() sol2 = Solution2() #TT = int(input()) for test_case in range(1): N, M = input().split() a = [] for _ in range(int(N)): a.append(input()) #b = [int(c) for c in input().split()] out = sol.solve(a) #print(' '.join([str(o) for o in out])) #print(str(out)) # out2 = sol2.solve(s) # for _ in range(100000): # rand = [random.randrange(60) for _ in range(10)] # out1 = sol.solve(rand) # out2 = sol2.solve(rand) # if out1 != out2: # print(rand, out1, out2) # break ```
5,085
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Tags: dfs and similar, dp, dsu, graphs, greedy Correct Solution: ``` n, m = map(int, input().split()) dishes = [0 for _ in range(n + m)] father = [-1 for _ in range(n + m)] e_out = dict() v_in = [0 for _ in range(n + m)] def get_father(n): if father[n] == -1: return n else: father[n] = get_father(father[n]) return father[n] compare_matrix = [] for i in range(n): compare_matrix.append(input()) for i in range(n): for j in range(m): if compare_matrix[i][j] == "=": fi = get_father(i) fj = get_father(j + n) if fi != fj: father[fj] = fi children = dict() for i in range(n + m): fi = get_father(i) if fi != i: if fi not in children: children[fi] = [i] else: children[fi].append(i) for i in range(n): for j in range(m): if compare_matrix[i][j] == "=": continue fi = get_father(i) fj = get_father(j + n) if fi == fj: print("NO") exit(0) if compare_matrix[i][j] == ">": v_in[fi] += 1 if fj in e_out: e_out[fj].append(fi) else: e_out[fj] = [fi] if compare_matrix[i][j] == "<": v_in[fj] += 1 if fi in e_out: e_out[fi].append(fj) else: e_out[fi] = [fj] # print(v_in) # print(e_out) score = 1 visited = [False for _ in range(n + m)] v_total = 0 q = [v for v in range(n + m) if v_in[v] == 0] while q: t = [] for i in q: dishes[i] = score v_total += 1 if i in children: for j in children[i]: dishes[j] = score v_total += 1 if i in e_out: for j in e_out[i]: v_in[j] -= 1 if v_in[j] == 0: t.append(j) q = t score += 1 if v_total < n + m: print("NO") exit(0) print("YES") for i in dishes[:n]: print(i, end=" ") print() for i in dishes[n:n + m]: print(i, end=" ") ```
5,086
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Tags: dfs and similar, dp, dsu, graphs, greedy Correct Solution: ``` """Codeforces 1131D """ from sys import * from typing import * from collections import * r, c = [int(i) for i in stdin.readline().strip().split(' ')] a = [stdin.readline().strip() for i in range(r)] def L(i: int) -> int: return i def R(i: int) -> int: return r + i parent = [0] * (r + c) for i in range(r): parent[L(i)] = L(i) for i in range(c): parent[R(i)] = R(i) def find(i: int) -> int: parent[i] = i if parent[i] == i else find(parent[i]) return parent[i] def union(i: int, j: int): parent[find(i)] = find(j) for i in range(r): for j in range(c): if a[i][j] == '=': union(L(i), R(j)) less_than = [[] for i in range(r + c)] for i in range(r): for j in range(c): if a[i][j] == '<': less_than[find(R(j))].append(find(L(i))) elif a[i][j] == '>': less_than[find(L(i))].append(find(R(j))) score = {} color = {} no_solution = set() def f(i: int) -> int: if i not in color: color[i] = 'gray' elif color[i] == 'gray': no_solution.add(True) else: return score[i] if no_solution: return 0 score[i] = 1 + max([f(j) for j in less_than[i]], default=0) color[i] = 'black' return score[i] ans1 = [f(find(L(i))) for i in range(r)] ans2 = [f(find(R(i))) for i in range(c)] if no_solution: print('No') else: print('Yes') print(*ans1) print(*ans2) ```
5,087
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Submitted Solution: ``` import os from io import BytesIO #input = BytesIO(os.read(0, os.fstat(0).st_size)).readline from itertools import product class CYCLE(Exception): ... debug_print = lambda *args: None def solve(n, m, gs): def union(u, v): p, q = find(u), find(v) if p == q: return if rank[p] < rank[q]: p, q = q, p if rank[p] == rank[q]: rank[p] += 1 parent[q] = p def find(u): if parent[u] == u: return u else: p = find(parent[u]) parent[u] = p return p rank = [0] * (n + m) parent = list(range(n + m)) for i, j in product(range(n), range(m)): if gs[i][j] == "=": union(i, n + j) vertices = set(parent) v_sz = len(vertices) g = [set() for _ in range(n + m)] for i, j in product(range(n), range(m)): c = gs[i][j] i, j = parent[i], parent[n + j] if c == "<": g[i].add(j) elif c == ">": g[j].add(i) debug_print(vertices, g) NIL, VISITED, FINAL = 0, 1, 2 state = [NIL] * (n + m) toposort_stack = [] def visit(v): debug_print(v) if state[v] == VISITED: raise CYCLE state[v] = VISITED for u in g[v]: if state[u] != FINAL: visit(u) state[v] = FINAL toposort_stack.append(v) try: for v in vertices: if state[v] == FINAL: continue visit(v) except CYCLE: print('No') return debug_print(toposort_stack) layer = [1] * (n + m) while toposort_stack: v = toposort_stack.pop() for u in g[v]: layer[u] = max(layer[u], layer[v]+1) print('Yes') out = [] for i in range(n): out.append(str(layer[parent[i]])) print(' '.join(out)) out = [] for j in range(m): out.append(str(layer[parent[n + j]])) print(' '.join(out)) def solve_from_stdin(): n, m = map(int, input().split()) gs = [] for _ in range(n): gs.append(input()) solve(n, m, gs) solve_from_stdin() ``` Yes
5,088
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Submitted Solution: ``` class mergefind: def __init__(self,n): self.parent = list(range(n)) self.size = [1]*n self.num_sets = n def find(self,a): to_update = [] while a != self.parent[a]: to_update.append(a) a = self.parent[a] for b in to_update: self.parent[b] = a return self.parent[a] def merge(self,a,b): a = self.find(a) b = self.find(b) if a==b: return if self.size[a]<self.size[b]: a,b = b,a self.num_sets -= 1 self.parent[b] = a self.size[a] += self.size[b] def set_size(self, a): return self.size[self.find(a)] def __len__(self): return self.num_sets def toposort(C, n): indeg = [0]*n for i,neighs in enumerate(C): for neigh in neighs: indeg[neigh] += 1 S = [i for i in range(n) if indeg[i] == 0] nparent = indeg[:] topo = [] while S: cur = S.pop() topo.append(cur) for neigh in C[cur]: nparent[neigh] -= 1 if nparent[neigh] == 0: S.append(neigh) nparent[cur] = -1 return topo n,m = map(int,input().split()) A = [input() for _ in range(n)] mf = mergefind(n+m) # merge equal elements for i in range(n): for j in range(m): if A[i][j] == '=': mf.merge(i,n+j) # Connections: smaller -> larger C = [set() for _ in range(n+m)] for i in range(n): for j in range(m): if A[i][j] == '<': C[mf.find(i)].add(mf.find(n+j)) elif A[i][j] == '>': C[mf.find(n+j)].add(mf.find(i)) # Walk through graph in toposort order # What I'm pointing to must be at least # my value + 1 D = [1]*(n+m) for cur in toposort(C, n+m): for neigh in C[cur]: D[neigh] = max(D[neigh], D[cur]+1) # Propagate values within equal clusters D = [D[mf.find(i)] for i in range(n+m)] # Validate answer ok = True for i in range(n): for j in range(m): if A[i][j] == '<': if D[i] >= D[n+j]: ok = False elif A[i][j] == '>': if D[i] <= D[n+j]: ok = False else: if D[i] != D[n+j]: ok = False if ok: print('Yes') print(*D[:n]) print(*D[n:]) else: print('No') ``` Yes
5,089
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Submitted Solution: ``` import sys sys.setrecursionlimit(2000) def dfs1(v, mintime): localtime = mintime vis1[v] = 1 for v2 in range(m): if a[v][v2] == ">": if not vis2[v2]: dfs2(v2, 1) localtime = max(localtime, time2[v2] + 1) for v2 in range(m): if a[v][v2] == "=": if not vis2[v2]: dfs2(v2, localtime) localtime = max(localtime, time2[v2]) time1[v] = localtime def dfs2(v, mintime): localtime = mintime vis2[v] = 1 for v2 in range(n): if a[v2][v] == "<": if not vis1[v2]: dfs1(v2, 1) localtime = max(localtime, time1[v2] + 1) for v2 in range(n): if a[v2][v] == "=": if not vis1[v2]: dfs1(v2, localtime) localtime = max(localtime, time1[v2]) time2[v] = localtime n, m = map(int, input().split()) a = [input() for i in range(n)] time1 = [0] * n time2 = [0] * m vis1 = [0] * n vis2 = [0] * m time = 0 try: for v in range(n): if not time1[v]: dfs1(v, 1) for v in range(m): if not time2[v]: dfs2(v, 1) correct = True for v1 in range(n): for v2 in range(m): if a[v1][v2] == "=" and time1[v1] != time2[v2]: correct = False if a[v1][v2] == ">" and time1[v1] <= time2[v2]: correct = False if a[v1][v2] == "<" and time1[v1] >= time2[v2]: correct = False if correct: print("Yes") print(*time1) print(*time2) else: print("No") except RecursionError: print("No") ``` Yes
5,090
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Submitted Solution: ``` class mergefind: def __init__(self,n): self.parent = list(range(n)) self.size = [1]*n self.num_sets = n def find(self,a): to_update = [] while a != self.parent[a]: to_update.append(a) a = self.parent[a] for b in to_update: self.parent[b] = a return self.parent[a] def merge(self,a,b): a = self.find(a) b = self.find(b) if a==b: return if self.size[a]<self.size[b]: a,b = b,a self.num_sets -= 1 self.parent[b] = a self.size[a] += self.size[b] def set_size(self, a): return self.size[self.find(a)] def __len__(self): return self.num_sets def toposort(C, n): indeg = [0]*n for i,neighs in enumerate(C): for neigh in neighs: indeg[neigh] += 1 S = [i for i in range(n) if indeg[i] == 0] nparent = indeg[:] topo = [] while S: cur = S.pop() topo.append(cur) for neigh in C[cur]: nparent[neigh] -= 1 if nparent[neigh] == 0: S.append(neigh) # nparent[cur] = -1 return topo n,m = map(int,input().split()) A = [input() for _ in range(n)] mf = mergefind(n+m) # merge equal elements for i in range(n): for j in range(m): if A[i][j] == '=': mf.merge(i,n+j) # Connections: smaller -> larger C = [set() for _ in range(n+m)] for i in range(n): for j in range(m): if A[i][j] == '<': C[mf.find(i)].add(mf.find(n+j)) elif A[i][j] == '>': C[mf.find(n+j)].add(mf.find(i)) # Walk through graph in toposort order # What I'm pointing to must be at least # my value + 1 D = [1]*(n+m) for cur in toposort(C, n+m): for neigh in C[cur]: D[neigh] = max(D[neigh], D[cur]+1) # Propagate values within equal clusters D = [D[mf.find(i)] for i in range(n+m)] # Validate answer ok = True for i in range(n): for j in range(m): if A[i][j] == '<': if D[i] >= D[n+j]: ok = False elif A[i][j] == '>': if D[i] <= D[n+j]: ok = False else: if D[i] != D[n+j]: ok = False if ok: print('Yes') print(*D[:n]) print(*D[n:]) else: print('No') ``` Yes
5,091
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Submitted Solution: ``` n, m = map(int, input().split()) g = [[] for i in range(n + m)] table = [] for i in range(n): table.append(input().strip()) for i in range(n): for j in range(m): if table[i][j] == "<": g[i].append((n + j, False)) elif table[i][j] == ">": g[n + j].append((i, False)) else: g[n + j].append((i, True)) g[i].append((n + j, True)) sorted_ver = [] visited = [False] * (n + m) def dfs(v): visited[v] = True for i in g[v]: if not visited[i[0]]: dfs(i[0]) sorted_ver.append(v) for i in range(n + m): if not visited[i]: dfs(i) sorted_ver.reverse() scores = [-1] * (m + n) visited = [False] * (n + m) res = [] def dfs(v, score): scores[v] = score for i in g[v]: if i[1]: if scores[i[0]] != score and scores[i[0]] != -1: print("No") exit() elif scores[i[0]] == -1: scores[i[0]] = score dfs(i[0], score) else: if scores[i[0]] == -1: dfs(i[0], score + 1) for i in sorted_ver: if scores[i] == -1: dfs(i, 1) for i in range(n): print(scores[i], end=" ") print() for i in range(n, n + m): print(scores[i], end=" ") ``` No
5,092
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Submitted Solution: ``` r,c = map(int, input().split()) R = [None for i in range(0,r)] C = [None for i in range(0,c)] ans = True for i in range(0,r): s = input().split()[0] s = list(s) for j in range(0,c): if s[j] == '=': if R[i] is not None and C[j] is not None and R[i] != C[j]: ans = False elif R[i] is not None: C[j] = R[i] elif C[j] is not None: R[i] = C[j] else: R[i] = 1 C[j] = 1 elif s[j] == '>': if R[i] is not None and C[j] is not None and R[i] <= C[j]: ans = False elif R[i] is not None: C[j] = R[i] - 1 elif C[j] is not None: R[i] = C[j] + 1 else: R[i] = 2 C[j] = 1 elif s[j] == '<': if R[i] is not None and C[j] is not None and R[i] >= C[j]: ans = False elif R[i] is not None: C[j] = R[i] + 1 elif C[j] is not None: R[i] = C[j] - 1 else: R[i] = 1 C[j] = 2 mini = 1 for i in R: mini = min(mini, i) for i in C: mini = min(mini, i) add = 1-mini for i in range(0,len(R)): R[i]+=add for j in range(0,len(C)): C[j]+=add if ans: print("Yes") print(str(R).replace(",","").replace("[",'').replace("]",'')) print(str(C).replace(",","").replace("[",'').replace("]",'')) else: print("No") ``` No
5,093
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Submitted Solution: ``` import time n1, m2 = map(int, input().split()) tests = [] for i in range(n1): tests.append(list(input())) #print (tests) begin = time.time() #print("---") marks1 = [] result1 = [] for i in range(n1): marks1.append([i,0.0]) result1.append(0) marks2 = [] result2 = [] for j in range(m2): marks2.append([j,0.0]) result2.append(0) for i in range(n1): for j in range(m2): test = tests[i][j] if test == ">": marks1[i][1] += 1.0 elif test == "<": marks2[j][1] += 1.0 else: marks1[i][1] += 0.0001 marks2[j][1] += 0.0001 marks1.sort(key=lambda val: val[1]) marks2.sort(key=lambda val: val[1]) #print(marks1) #print(marks2) i = 0 j = 0 value = 0 lastmark = -1 lastItem = [0,0] while i < n1 or j < m2: LetAdd = 0 if i < n1 and j < m2: if marks1[i][1] <= marks2[j][1]: LetAdd = 1 else: LetAdd = 2 elif i < n1: LetAdd = 1 else: LetAdd = 2 if LetAdd == 1: if marks1[i][1] != lastmark and lastItem[0] != 2 or lastItem[0] == 2 and tests[marks1[i][0]][lastItem[1]] != '=': lastmark = marks1[i][1] value += 1 result1[marks1[i][0]] = value lastItem = [1,i] i += 1 else: if marks2[j][1] != lastmark and lastItem[0] != 1 or lastItem[0] == 1 and tests[lastItem[1]][marks2[j][0]] != '=': # print(lastItem[1], j, tests[lastItem[1]][marks2[j][0]]) lastmark = marks2[j][1] value += 1 result2[marks2[j][0]] = value lastItem = [2,j] j += 1 CheckCorrect = True for i in range(n1): for j in range(m2): test = tests[i][j] if test == ">": if result1[i] <= result2[j]: CheckCorrect = False elif test == "<": if result1[i] >= result2[j]: CheckCorrect = False else: if result1[i] != result2[j]: CheckCorrect = False #print("---") #print("Time: ", time.time() - begin) if CheckCorrect: print ("Yes") print (*result1) print (*result2) else: print ("No") ``` No
5,094
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it. Submitted Solution: ``` import sys input=sys.stdin.readline n,m=map(int,input().split()) grid=[] for i in range(n): s=input() grid.append(s) a=[] b=[] for i in range(n): tmp=0 tmp2=0 for j in range(m): if grid[i][j]=='<': tmp+=1 if grid[i][j]=='>': tmp2-=1 a.append([i,tmp,tmp2]) for i in range(m): tmp=0 tmp2=0 for j in range(n): if grid[j][i]=='<': tmp+=1 if grid[j][i]=='>': tmp2-=1 b.append([i,tmp,tmp2]) a.sort(key=lambda thing: thing[1]) b.sort(key=lambda thing: thing[1]) a.sort(key=lambda thing: thing[2]) b.sort(key=lambda thing: thing[2]) a.reverse() b.reverse() pointer1=0 pointer2=0 ans1=[0]*n ans2=[0]*m curr=1 last1=-1 last2=-1 flag=0 while pointer1<n and pointer2<m: k=a[pointer1][0] l=b[pointer2][0] t=grid[k][l] r=grid[a[pointer1-1][0]][l] s=grid[k][b[pointer2-1][0]] if t=='<': if pointer1!=0 and r!='>': curr-=1 ans1[k]=curr last=r curr+=1 pointer1+=1 elif t=='>': if pointer2!=0 and s!='<': curr-=1 ans2[l]=curr curr+=1 pointer2+=1 else: if (pointer1!=0 and r=='=') or (pointer2!=0 and s=='='): curr-=1 ans1[k]=curr ans2[l]=curr curr+=1 pointer1+=1 pointer2+=1 if pointer1<n: if pointer1!=0 and grid[a[pointer1-1][0]][b[m-1][0]]!='>': curr-=1 tl=0 if not tl and grid[a[pointer1][0]][b[m-1][0]]=='>': tl=1 while pointer1<n: if not tl and grid[a[pointer1][0]][b[m-1][0]]=='>': curr+=1 tl=1 k=a[pointer1][0] ans1[k]=curr pointer1+=1 while pointer2<m: if pointer2!=0 and grid[a[n-1][0]][b[pointer2-1][0]]!='<': curr-=1 tl=0 if not tl and grid[a[n-1][0]][b[pointer2-1][0]]=='<': tl=1 while pointer2<m: if not tl and grid[a[n-1][0]][b[pointer2-1][0]]=='<': curr+=1 tl=1 k=b[pointer2][0] ans2[k]=curr pointer+=1 for i in range(n): if ans1[i]==0: ans1[i]=1 for i in range(m): if ans2[i]==0: ans2[i]=1 for i in range(n): for j in range(m): p=grid[i][j] if p=='<': if ans1[i]>=ans2[j]: flag=1 break elif p=='>': if ans1[i]<=ans2[j]: flag=1 break else: if ans1[i]!=ans2[j]: flag=1 break if flag: break if flag: print('No') else: print('Yes') print(' '.join(map(str,ans1))) print(' '.join(map(str,ans2))) ``` No
5,095
Provide tags and a correct Python 3 solution for this coding contest problem. A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her. Given an array a of length n, consisting only of the numbers 0 and 1, and the number k. Exactly k times the following happens: * Two numbers i and j are chosen equiprobable such that (1 ≤ i < j ≤ n). * The numbers in the i and j positions are swapped. Sonya's task is to find the probability that after all the operations are completed, the a array will be sorted in non-decreasing order. She turned to you for help. Help Sonya solve this problem. It can be shown that the desired probability is either 0 or it can be represented as P/Q, where P and Q are coprime integers and Q not≡ 0~\pmod {10^9+7}. Input The first line contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ 10^9) — the length of the array a and the number of operations. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 1) — the description of the array a. Output If the desired probability is 0, print 0, otherwise print the value P ⋅ Q^{-1} \pmod {10^9+7}, where P and Q are defined above. Examples Input 3 2 0 1 0 Output 333333336 Input 5 1 1 1 1 0 0 Output 0 Input 6 4 1 0 0 1 1 0 Output 968493834 Note In the first example, all possible variants of the final array a, after applying exactly two operations: (0, 1, 0), (0, 0, 1), (1, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 1), (1, 0, 0), (0, 1, 0). Therefore, the answer is 3/9=1/3. In the second example, the array will not be sorted in non-decreasing order after one operation, therefore the answer is 0. Tags: combinatorics, dp, matrices, probabilities Correct Solution: ``` N, T = map(int, input().split()) A = [int(a) for a in input().split()] if sum(A) > N//2: A = [1-a for a in A][::-1] K = sum(A) S = sum(A[-K:]) M = K + 1 P = 10**9+7 inv = pow(N*(N-1)//2, P-2, P) X = [[0]*M for _ in range(M)] for i in range(M): if i > 0: X[i-1][i] = ((K-i+1)**2*inv)%P if i < M-1: X[i+1][i] = (N-2*K+i+1)*(i+1)*inv%P X[i][i] = (1-((K-i)**2*inv)-(N-2*K+i)*(i)*inv)%P def ddd(n): for i in range(1, 100): if (n*i%P) < 100: return (n*i%P), i return -1, -1 def poww(MM, n): if n == 1: return MM if n % 2: return mult(poww(MM, n-1), MM) return poww(mult(MM,MM), n//2) def mult(M1, M2): Y = [[0] * M for _ in range(M)] for i in range(M): for j in range(M): for k in range(M): Y[i][j] += M1[i][k] * M2[k][j] Y[i][j] %= P return Y X = poww(X, T) print(X[S][K]) ```
5,096
Provide tags and a correct Python 3 solution for this coding contest problem. A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her. Given an array a of length n, consisting only of the numbers 0 and 1, and the number k. Exactly k times the following happens: * Two numbers i and j are chosen equiprobable such that (1 ≤ i < j ≤ n). * The numbers in the i and j positions are swapped. Sonya's task is to find the probability that after all the operations are completed, the a array will be sorted in non-decreasing order. She turned to you for help. Help Sonya solve this problem. It can be shown that the desired probability is either 0 or it can be represented as P/Q, where P and Q are coprime integers and Q not≡ 0~\pmod {10^9+7}. Input The first line contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ 10^9) — the length of the array a and the number of operations. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 1) — the description of the array a. Output If the desired probability is 0, print 0, otherwise print the value P ⋅ Q^{-1} \pmod {10^9+7}, where P and Q are defined above. Examples Input 3 2 0 1 0 Output 333333336 Input 5 1 1 1 1 0 0 Output 0 Input 6 4 1 0 0 1 1 0 Output 968493834 Note In the first example, all possible variants of the final array a, after applying exactly two operations: (0, 1, 0), (0, 0, 1), (1, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 1), (1, 0, 0), (0, 1, 0). Therefore, the answer is 3/9=1/3. In the second example, the array will not be sorted in non-decreasing order after one operation, therefore the answer is 0. Tags: combinatorics, dp, matrices, probabilities Correct Solution: ``` import sys; input=sys.stdin.readline # print(input()) N, T = map(int, input().split()) A = [int(a) for a in input().split()] if sum(A) > N//2: A = [1-a for a in A][::-1] K = sum(A) S = sum(A[-K:]) M = K + 1 P = 10**9+7 inv = pow(N*(N-1)//2, P-2, P) X = [[0]*M for _ in range(M)] for i in range(M): if i > 0: X[i-1][i] = ((K-i+1)**2*inv)%P if i < M-1: X[i+1][i] = (N-2*K+i+1)*(i+1)*inv%P X[i][i] = (1-((K-i)**2*inv)-(N-2*K+i)*(i)*inv)%P # def ddd(n): # for i in range(1, 100): # if (n*i%P) < 100: # return (n*i%P), i # return -1, -1 def poww(MM, n): if n == 1: return MM if n % 2: return mult(poww(MM, n-1), MM) return poww(mult(MM,MM), n//2) def mult(M1, M2): Y = [[0] * M for _ in range(M)] for i in range(M): for j in range(M): for k in range(M): Y[i][j] += M1[i][k] * M2[k][j] Y[i][j] %= P return Y X = poww(X, T) print(X[S][K]) ```
5,097
Provide tags and a correct Python 3 solution for this coding contest problem. A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her. Given an array a of length n, consisting only of the numbers 0 and 1, and the number k. Exactly k times the following happens: * Two numbers i and j are chosen equiprobable such that (1 ≤ i < j ≤ n). * The numbers in the i and j positions are swapped. Sonya's task is to find the probability that after all the operations are completed, the a array will be sorted in non-decreasing order. She turned to you for help. Help Sonya solve this problem. It can be shown that the desired probability is either 0 or it can be represented as P/Q, where P and Q are coprime integers and Q not≡ 0~\pmod {10^9+7}. Input The first line contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ 10^9) — the length of the array a and the number of operations. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 1) — the description of the array a. Output If the desired probability is 0, print 0, otherwise print the value P ⋅ Q^{-1} \pmod {10^9+7}, where P and Q are defined above. Examples Input 3 2 0 1 0 Output 333333336 Input 5 1 1 1 1 0 0 Output 0 Input 6 4 1 0 0 1 1 0 Output 968493834 Note In the first example, all possible variants of the final array a, after applying exactly two operations: (0, 1, 0), (0, 0, 1), (1, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 1), (1, 0, 0), (0, 1, 0). Therefore, the answer is 3/9=1/3. In the second example, the array will not be sorted in non-decreasing order after one operation, therefore the answer is 0. Tags: combinatorics, dp, matrices, probabilities Correct Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """Codeforces Round #553 (Div. 2) Problem F. Sonya and Informatics :author: Kitchen Tong :mail: kctong529@gmail.com Please feel free to contact me if you have any question regarding the implementation below. """ __version__ = '1.8' __date__ = '2019-04-21' import sys def binom_dp(): dp = [[-1 for j in range(110)] for i in range(110)] def calculate(n, k): if n < k: return 0 if n == k or k == 0: return 1 if dp[n][k] > 0: return dp[n][k] else: dp[n][k] = calculate(n-1, k-1) + calculate(n-1, k) return dp[n][k] return calculate def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m def multiply(A, B, mod): if not hasattr(B[0], '__len__'): C = [sum(aij * B[j] % mod for j, aij in enumerate(ai)) for ai in A] else: C = [[0 for col in range(len(B[0]))] for row in range(len(A))] len_A = len(A) len_B = len(B) for row in range(len_A): if sum(A[row]) == 0: continue for col in range(len_B): C[row][col] = sum(A[row][k] * B[k][col] for k in range(len_B)) % mod return C def memoize(func): memo = {} def wrapper(*args): M, n, mod = args if n not in memo: memo[n] = func(M, n, mod) return memo[n] return wrapper @memoize def matrix_pow(M, n, mod): # print(f'n is {n}') if n == 2: return multiply(M, M, mod) if n == 1: return M sub_M = matrix_pow(M, n//2, mod) if n % 2 == 0: return multiply(sub_M, sub_M, mod) return multiply(sub_M, matrix_pow(M, n - n//2, mod), mod) def solve(n, k, a, binom, mod): ones = sum(a) zeros = n - ones M = [[0 for col in range(zeros+1)] for row in range(zeros+1)] for row in range(max(0, zeros-ones), zeros+1): pre_zeros = row pre_ones = zeros - pre_zeros post_zeros = pre_ones post_ones = ones - pre_ones M[row][row] = (pre_ones * post_ones + pre_zeros * post_zeros + binom(zeros, 2) + binom(ones, 2)) if row > max(0, zeros-ones): M[row-1][row] = pre_zeros * post_ones if row < zeros: M[row+1][row] = post_zeros * pre_ones M = [matrix_pow(M, k, mod)[-1]] b = [0] * (zeros + 1) b[zeros - sum(a[:zeros])] = 1 C = multiply(M, b, mod) return C[-1] def main(argv=None): mod = int(1e9) + 7 n, k = list(map(int, input().split())) a = list(map(int, input().split())) binom = binom_dp() P = solve(n, k, a, binom, mod) if P == 0: print(0) else: Q = pow(binom(n, 2), k, mod) print(P * modinv(Q, mod) % mod) return 0 if __name__ == "__main__": STATUS = main() sys.exit(STATUS) ```
5,098
Provide tags and a correct Python 3 solution for this coding contest problem. A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her. Given an array a of length n, consisting only of the numbers 0 and 1, and the number k. Exactly k times the following happens: * Two numbers i and j are chosen equiprobable such that (1 ≤ i < j ≤ n). * The numbers in the i and j positions are swapped. Sonya's task is to find the probability that after all the operations are completed, the a array will be sorted in non-decreasing order. She turned to you for help. Help Sonya solve this problem. It can be shown that the desired probability is either 0 or it can be represented as P/Q, where P and Q are coprime integers and Q not≡ 0~\pmod {10^9+7}. Input The first line contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ 10^9) — the length of the array a and the number of operations. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 1) — the description of the array a. Output If the desired probability is 0, print 0, otherwise print the value P ⋅ Q^{-1} \pmod {10^9+7}, where P and Q are defined above. Examples Input 3 2 0 1 0 Output 333333336 Input 5 1 1 1 1 0 0 Output 0 Input 6 4 1 0 0 1 1 0 Output 968493834 Note In the first example, all possible variants of the final array a, after applying exactly two operations: (0, 1, 0), (0, 0, 1), (1, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 1), (1, 0, 0), (0, 1, 0). Therefore, the answer is 3/9=1/3. In the second example, the array will not be sorted in non-decreasing order after one operation, therefore the answer is 0. Tags: combinatorics, dp, matrices, probabilities Correct Solution: ``` M = 10 ** 9 + 7 n, k = map(int, input().split()) a = list(map(int, input().split())) z, o = a.count(0), a.count(1) d = pow(n * (n - 1) // 2, M - 2, M) if z > o: o, z = z, o a = [1 - x for x in a][::-1] res = [[0] * (z + 1) for i in range(z + 1)] tf = [[0] * (z + 1) for i in range(z + 1)] for i in range(z + 1): res[i][i] = 1 tf[i][i] = (z * (z - 1) // 2 + o * (o - 1) // 2 + i * (z - i) + (z - i) * (o - z + i)) * d % M if i < z: tf[i + 1][i] = (z - i) * (z - i) * d % M if i: tf[i - 1][i] = i * (o - z + i) * d % M def mul(a, b): t = [[0] * (z + 1) for i in range(z + 1)] for i in range(z + 1): for k in range(z + 1): for j in range(z + 1): t[i][j] = (t[i][j] + a[i][k] * b[k][j]) % M return t while k: if k & 1: res = mul(res, tf) tf = mul(tf, tf) k >>= 1 print(res[-1][a[:z].count(0)]) ```
5,099