message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image>
instruction
0
49,738
13
99,476
Tags: divide and conquer, dsu, graphs, sortings, trees Correct Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) g = [[] for i in range(n)] for i in range(n - 1): v, u = map(int, input().split()) v -= 1 u -= 1 g[v].append(u) g[u].append(v) dp = [[] for i in range(n)] d = [1 for i in range(n)] def dfs(v, p = -1): dp[v].append(a[v]) for u in g[v]: if u == p: continue dfs(u, v) tmp = [-10**18 for i in range(max(d[v], d[u] + 1))] for i in range(d[v]): for j in range(max(0, k - i), d[u]): tmp[min(i, j + 1)] = max(tmp[min(i, j + 1)], dp[v][i] + dp[u][j]) for i in range(d[u]): tmp[i + 1] = max(tmp[i + 1], dp[u][i]) for i in range(d[v]): dp[v][i] = max(dp[v][i], tmp[i]) dp[v] += tmp[d[v]:] d[v] = max(d[v], d[u] + 1) for i in range(d[v] - 1, 0, -1): dp[v][i - 1] = max(dp[v][i - 1], dp[v][i]) dfs(0) print(max(dp[0])) ```
output
1
49,738
13
99,477
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image>
instruction
0
49,739
13
99,478
Tags: divide and conquer, dsu, graphs, sortings, trees Correct Solution: ``` class UnionFind(): def __init__(self, n): self.n = n self.root = [-1]*(n+1) self.rnk = [0]*(n+1) def Find_Root(self, x): if(self.root[x] < 0): return x else: self.root[x] = self.Find_Root(self.root[x]) return self.root[x] def Unite(self, x, y): x = self.Find_Root(x) y = self.Find_Root(y) if(x == y): return elif(self.rnk[x] > self.rnk[y]): self.root[x] += self.root[y] self.root[y] = x else: self.root[y] += self.root[x] self.root[x] = y if(self.rnk[x] == self.rnk[y]): self.rnk[y] += 1 def isSameGroup(self, x, y): return self.Find_Root(x) == self.Find_Root(y) def Count(self, x): return -self.root[self.Find_Root(x)] import sys input = sys.stdin.readline from bisect import bisect_right N, M = map(int, input().split()) uni = UnionFind(N+1) Edges = {} for _ in range(N-1): a, b, w = map(int, input().split()) if not w in Edges: Edges[w] = [(a, b)] else: Edges[w].append((a, b)) Query = list(map(int, input().split())) Weights = sorted(list(Edges.keys())) Score = [0] score = 0 for w in Weights: for a, b in Edges[w]: c1 = uni.Count(a) c2 = uni.Count(b) c = c1 + c2 score += c*(c-1)//2 - c1*(c1-1)//2 - c2*(c2-1)//2 uni.Unite(a, b) Score.append(score) ans = [] for q in Query: ind = bisect_right(Weights, q) ans.append(Score[ind]) print(*ans) ```
output
1
49,739
13
99,479
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image>
instruction
0
49,740
13
99,480
Tags: divide and conquer, dsu, graphs, sortings, trees Correct Solution: ``` from sys import setrecursionlimit as SRL, stdin SRL(10 ** 7) rd = stdin.readline rrd = lambda: map(int, rd().strip().split()) fa = [i for i in range(200005)] s = [1] * 200005 def find(x): t = [] while fa[x] != x: t.append(x) x = fa[x] for i in t: fa[i] = x return fa[x] ans = [0] * 200005 n, q = rrd() w = [] for i in range(n - 1): x, y, z = rrd() w.append([z, x, y]) w.sort(key=lambda x: x[0]) for x in w: u = find(x[1]) v = find(x[2]) ans[x[0]] += s[u] * s[v] fa[u] = v s[v] += s[u] for i in range(1, 200001): ans[i] += ans[i - 1] q = list(rrd()) for x in q: print(ans[x], end=' ') ```
output
1
49,740
13
99,481
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image>
instruction
0
49,741
13
99,482
Tags: divide and conquer, dsu, graphs, sortings, trees Correct Solution: ``` from collections import defaultdict import sys sys.setrecursionlimit(10**6) readline = sys.stdin.readline N, M = map(int, readline().split()) E = [] for i in range(N-1): u, v, w = map(int, readline().split()) E.append((w, u-1, v-1)) E.sort() Q = set() MP = defaultdict(list) for i, q in enumerate(map(int, readline().split())): MP[q].append(i) Q.add(q) Q = list(Q) Q.sort() def fact(N): return N*fact(N-1) % 100 if N > 1 else 1 fact(2000) def root(x): if x == p[x]: return x y = x while y != p[y]: y = p[y] while x != y: p[x], x = y, p[x] return y *p, = range(N) sz = [1]*N c = 0 def unite(x, y): global c px = root(x); py = root(y) if px == py: return 0 c += sz[px] * sz[py] if sz[px] < sz[py]: p[py] = px sz[px] += sz[py] else: p[px] = py sz[py] += sz[px] return 1 k = 0 ans = [N*(N-1)//2]*M L = len(Q) for w, u, v in E: while k < L and Q[k] < w: e = Q[k] for i in MP[e]: ans[i] = c k += 1 unite(u, v) sys.stdout.write(" ".join(map(str, ans))) sys.stdout.write("\n") ```
output
1
49,741
13
99,483
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image>
instruction
0
49,742
13
99,484
Tags: divide and conquer, dsu, graphs, sortings, trees Correct Solution: ``` import typing from bisect import bisect_right, bisect_left import sys def input(): return sys.stdin.readline().rstrip() class DSU: ''' Implement (union by size) + (path halving) Reference: Zvi Galil and Giuseppe F. Italiano, Data structures and algorithms for disjoint set union problems ''' def __init__(self, n: int = 0) -> None: self._n = n self.parent_or_size = [-1] * n def merge(self, a: int, b: int) -> int: assert 0 <= a < self._n assert 0 <= b < self._n x = self.leader(a) y = self.leader(b) if x == y: return x if -self.parent_or_size[x] < -self.parent_or_size[y]: x, y = y, x self.parent_or_size[x] += self.parent_or_size[y] self.parent_or_size[y] = x return x def same(self, a: int, b: int) -> bool: assert 0 <= a < self._n assert 0 <= b < self._n return self.leader(a) == self.leader(b) def leader(self, a: int) -> int: assert 0 <= a < self._n parent = self.parent_or_size[a] while parent >= 0: if self.parent_or_size[parent] < 0: return parent self.parent_or_size[a], a, parent = ( self.parent_or_size[parent], self.parent_or_size[parent], self.parent_or_size[self.parent_or_size[parent]] ) return a def size(self, a: int) -> int: assert 0 <= a < self._n return -self.parent_or_size[self.leader(a)] def groups(self) -> typing.List[typing.List[int]]: leader_buf = [self.leader(i) for i in range(self._n)] result: typing.List[typing.List[int]] = [[] for _ in range(self._n)] for i in range(self._n): result[leader_buf[i]].append(i) return list(filter(lambda r: r, result)) def slv(): n, m = map(int, input().split()) dsu = DSU(n + 100) edge = [] for i in range(n - 1): u, v, w = map(int, input().split()) edge.append((u, v, w)) query = list(map(int, input().split())) edge.sort(key=lambda x: x[2]) tot = 0 costdata = [0] weightdata = [0] for u, v, w in edge: tot += dsu.size(u) * dsu.size(v) dsu.merge(u, v) costdata.append(tot) weightdata.append(w) ans = [] for q in query: cnt = bisect_right(weightdata, q) - 1 ans.append(costdata[cnt]) print(*ans) return def main(): t = 1 for i in range(t): slv() return if __name__ == "__main__": main() ```
output
1
49,742
13
99,485
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image>
instruction
0
49,743
13
99,486
Tags: divide and conquer, dsu, graphs, sortings, trees Correct Solution: ``` n,m=map(int,input().split()) dp=[] for i in range(n-1): u,v,w=map(int,input().split()) dp.append((w,u-1,v-1)) dp=sorted(dp) q=[int(x) for x in input().split()] pos=[] for i in range(m): pos.append(i) Q=sorted(zip(q,pos)) par=[] for i in range(0,n): par.append(i) rank=[1]*n def find(x): if(par[x]!=x): par[x]=find(par[x]) return par[x] global res res=0 def union(x,y): global res X=find(x) Y=find(y) if(rank[X]<rank[Y]): temp=X X=Y Y=temp res=res-(rank[X]*(rank[X]-1)//2) res=res-(rank[Y]*(rank[Y]-1)//2) rank[X]+=rank[Y] res=res+(rank[X]*(rank[X]-1)//2) par[Y]=X """if(X==Y): return if(rank[X]<rank[Y]): par[X]=Y elif(rank[X]>rank[Y]): par[Y]=X else: par[Y]=X rank[X]=rank[Y]+1""" ans=[0]*m ptr=0 for i in range(0,m): while(ptr<n-1 and dp[ptr][0]<=Q[i][0]): a=dp[ptr][1] b=dp[ptr][2] union(a,b) ptr+=1 ans[Q[i][1]]=res print(*ans) ```
output
1
49,743
13
99,487
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image> Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ def main(): n, m = map(int, input().split()) l = [] for i in range(n - 1): a1, b, c = map(int, input().split()) l.append((c, a1, b)) a = list(map(int, input().split())) e = a + [] l.sort() a.sort() p = [i for i in range(n + 1)] size = [1 for i in range(n + 1)] def get(a1): if p[a1] != a1: p[a1] = get(p[a1]) return p[a1] def union(a1, b): a1 = get(a1) b = get(b) if size[a1] < size[b]: a1, b = b, a1 p[a1] = b size[b] += size[a1] t = 0 ans = 0 de = defaultdict(int) for i in a: de[i] = (n * (n - 1)) // 2 i = 0 while (i < n - 1): if l[i][0] <= a[t]: if get(l[i][1]) != get(l[i][2]): c = size[get(l[i][2])] d = size[get(l[i][1])] ans += ((c + d) * ((c + d) - 1)) // 2 - (c * (c - 1)) // 2 - (d * (d - 1)) // 2 union(l[i][1], l[i][2]) i += 1 else: de[a[t]] = ans t += 1 if t == n: break for i in e: print(de[i], end=' ') t = threading.Thread(target=main) t.start() t.join() ```
instruction
0
49,744
13
99,488
Yes
output
1
49,744
13
99,489
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image> Submitted Solution: ``` n, m = map(int, input().split()) maxN = 2 * (10 ** 5) + 10 edges = [[] for i in range(0, maxN)] que = [[] for _ in range(0, maxN)] ans = [0] * m sz = [1 for _ in range(0, n)] p = [i for i in range(0, n)] total_sum = 0 def get(u): if p[u] == u: return u p[u] = get(p[u]) return p[u] def unite(u, v): u = get(u) v = get(v) if u == v: return global total_sum total_sum -= (sz[u] * (sz[u] - 1)) // 2 total_sum -= (sz[v] * (sz[v] - 1)) // 2 total_sum += ((sz[u] + sz[v]) * (sz[u] + sz[v] - 1)) // 2 if sz[u] < sz[v]: p[u] = v sz[v] += sz[u] else: p[v] = u sz[u] += sz[v] for i in range(1, n): u, v, w = map(int, input().split()) u -= 1 v -= 1 edges[w].append((u, v)) ques = list(map(int, input().split())) for i in range(0, m): que[ques[i]].append(i) for i in range(0, maxN): for u, v in edges[i]: unite(u, v) for id in que[i]: ans[id] = total_sum print(" ".join(str(x) for x in ans)) ```
instruction
0
49,745
13
99,490
Yes
output
1
49,745
13
99,491
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image> Submitted Solution: ``` """ Author - Satwik Tiwari . """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from functools import cmp_to_key # from itertools import * from heapq import * from math import gcd, factorial,floor,ceil,sqrt,log2 from copy import deepcopy from collections import deque from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def testcase(t): for pp in range(t): solve(pp) def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def modInverse(b): g = gcd(b, mod) if (g != 1): # print("Inverse doesn't exist") return -1 else: # If b and m are relatively prime, # then modulo inverse is b^(m-2) mode m return pow(b, mod - 2, mod) def power(x, y, p) : y%=(p-1) #not so sure about this. used when y>p-1. if p is prime. res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True inf = pow(10,20) mod = inf #=============================================================================================== # code here ;)) def bucketsort(order, seq): buckets = [0] * (max(seq) + 1) for x in seq: buckets[x] += 1 for i in range(len(buckets) - 1): buckets[i + 1] += buckets[i] new_order = [-1] * len(seq) for i in reversed(order): x = seq[i] idx = buckets[x] = buckets[x] - 1 new_order[idx] = i return new_order def ordersort(order, seq, reverse=False): bit = max(seq).bit_length() >> 1 mask = (1 << bit) - 1 order = bucketsort(order, [x & mask for x in seq]) order = bucketsort(order, [x >> bit for x in seq]) if reverse: order.reverse() return order def long_ordersort(order, seq): order = ordersort(order, [int(i & 0x7fffffff) for i in seq]) return ordersort(order, [int(i >> 31) for i in seq]) def multikey_ordersort(order, *seqs, sort=ordersort): for i in reversed(range(len(seqs))): order = sort(order, seqs[i]) return order class DisjointSetUnion: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.num_sets = n def find(self, a): acopy = a while a != self.parent[a]: a = self.parent[a] while acopy != a: self.parent[acopy], acopy = a, self.parent[acopy] return a def union(self, a, b): a, b = self.find(a), self.find(b) if a != b: 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 get_size(self, a): return self.size[self.find(a)] def __len__(self): return self.num_sets def do(a): return (a * (a-1)//2) def solve(case): n,m = sep() w = [] u = [] v = [] if(n == 1): ans = [0]*m print(' '.join(str(i) for i in ans)) return for i in range(n-1): l,r,ww = sep() u.append(l) v.append(r) w.append(ww) q = lis() ind = [i for i in range(n)] order = multikey_ordersort(range(n-1),w,u,v) order2 = multikey_ordersort(range(m),q) queries = [] for i in order2: queries.append((q[i],ind[i])) curr = 0 ans = [0]*(m) dsu = DisjointSetUnion(n+1) ind = 0 for i in order: while(ind < m and w[i] > queries[ind][0]): ans[queries[ind][1]] = curr ind += 1 curr -= do(dsu.get_size(u[i])) curr -= do(dsu.get_size(v[i])) dsu.union(u[i],v[i]) curr += do(dsu.get_size(u[i])) while (ind < m and inf > queries[ind][0]): ans[queries[ind][1]] = curr ind += 1 print(' '.join(str(i) for i in ans)) testcase(1) # testcase(int(inp())) ```
instruction
0
49,746
13
99,492
Yes
output
1
49,746
13
99,493
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image> Submitted Solution: ``` def find_ancestor(i, father): if father[i] == i: return i father[i] = find_ancestor(father[i], father) return father[i] def connect(i, j, father, n_child): i_anc = find_ancestor(i, father) j_anc = find_ancestor(j, father) if n_child[i_anc] > n_child[j_anc]: n_child[i_anc] += n_child[j_anc] father[j_anc] = i_anc else: n_child[j_anc] += n_child[i_anc] father[i_anc] = j_anc n, m = map(int, input().split()) edges = [] father = [i for i in range(n)] n_child = [1]*n for i in range(n-1): i, j, w = map(int, input().split()) edges.append((i-1, j-1, w)) edges.sort(key=lambda x: -x[2]) queries = list(map(int, input().split())) s_queries = sorted(queries) # final map the index to the query ans = {} w_limit = [] ans_cum = 0 for query in s_queries: while len(edges) and edges[-1][2] <= query: i, j, w = edges[-1] edges.pop() i_anc = find_ancestor(i, father) j_anc = find_ancestor(j, father) # it's tree father may not be same ans_cum += n_child[i_anc] * n_child[j_anc] connect(i, j, father, n_child) ans[query] = ans_cum print(" ".join(list(map(str, [ans[query] for query in queries])))) ```
instruction
0
49,747
13
99,494
Yes
output
1
49,747
13
99,495
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image> Submitted Solution: ``` import sys sys.setrecursionlimit(10**9) def find(a): if par[a]==a: return a par[a]=find(par[a]) return par[a] n,m=map(int,input().split()) ed=[] par=[i for i in range(n)] size=[1 for i in range(n)] for _ in range(n-1): a,b,c=map(int,input().split()) ed.append([a-1,b-1,c]) ed.sort(key=lambda x:x[2]) it=list(map(int,input().split())) it=[[i,j,0] for j,i in enumerate(it)] it.sort() ind=0 tot=0 j=0 #print(it) ss={} for i in it[:]: while ind<n-1: if ed[ind][2]<=i[0]: a=find(ed[ind][0]) b=find(ed[ind][1]) tot+=size[a]*size[b] # print(a,b,j,tot) if size[a]>=size[b]: par[b]=a size[a]+=size[b] else: par[a]=b size[b]+=a ind+=1 else: break it[j][2]=tot ss[it[j][1]]=tot j+=1 it.sort(key=lambda x:x[1]) aa=[i[2] for i in it] for i in range(len(it)): print(ss[i],end=" ") #print(*aa) ```
instruction
0
49,748
13
99,496
No
output
1
49,748
13
99,497
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image> Submitted Solution: ``` for i in range(30, 30): print('KEKE') ```
instruction
0
49,749
13
99,498
No
output
1
49,749
13
99,499
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image> Submitted Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) info = [list(map(int, input().split())) for i in range(n-1)] graph = [[] for i in range(n)] for i in range(n-1): tmp_a, tmp_b = info[i] tmp_a -= 1 tmp_b -= 1 graph[tmp_a].append(tmp_b) graph[tmp_b].append(tmp_a) def dfs(pos): is_leaf = True tmp = [] for next_pos in graph[pos]: if visited[next_pos]: continue visited[next_pos] = True is_leaf = False tmp.append(dfs(next_pos)) if not is_leaf: dp[pos][0] = a[pos] + max(dp[next_pos][k:]) tmp_sum = [0]*n for i in range(len(tmp)): for j in range(n): tmp_sum[j] += tmp[i][j] i = -1 while True: i += 1 if i > k-i-1: break for j in range(len(tmp)): dp[pos][i+1] = max(tmp[j][i] + tmp_sum[k-i-1] - tmp[j][k-i-1], dp[pos][i+1]) while True: dp[pos][i+1] = tmp_sum[i] i += 1 if i >= n-1: break for i in range(1, n)[::-1]: dp[pos][i-1] = max(dp[pos][i-1], dp[pos][i]) return dp[pos] else: dp[pos][0] = a[pos] return dp[pos] dp = [[0]*(n) for i in range(n)] visited = [False]*n visited[0] = True dfs(0) print(dp[0][0]) ```
instruction
0
49,750
13
99,500
No
output
1
49,750
13
99,501
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of vertices in the tree and the number of queries. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i β€” the labels of vertices it connects (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i) and the weight of the edge (1 ≀ w_i ≀ 2 β‹… 10^5). It is guaranteed that the given edges form a tree. The last line of the input contains m integers q_1, q_2, ..., q_m (1 ≀ q_i ≀ 2 β‹… 10^5), where q_i is the maximum weight of an edge in the i-th query. Output Print m integers β€” the answers to the queries. The i-th value should be equal to the number of pairs of vertices (u, v) (u < v) such that the maximum weight of an edge on a simple path between u and v doesn't exceed q_i. Queries are numbered from 1 to m in the order of the input. Examples Input 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 Output 21 7 15 21 3 Input 1 2 1 2 Output 0 0 Input 3 3 1 2 1 2 3 2 1 3 2 Output 1 3 3 Note The picture shows the tree from the first example: <image> Submitted Solution: ``` from collections import defaultdict N, M = map(int, input().split()) E = [] for i in range(N-1): u, v, w = map(int, input().split()) E.append((w, u-1, v-1)) E.sort() Q = set() MP = defaultdict(list) for i, q in enumerate(map(int, input().split())): MP[q].append(i) Q.add(q) Q = list(Q) Q.sort() def root(x): if x == p[x]: return x p[x] = y = root(p[x]) return y *p, = range(N) sz = [1]*N c = 0 def unite(x, y): global c px = root(x); py = root(y) if px == py: return 0 if sz[px] < sz[py]: p[py] = px c += sz[px] * sz[py] sz[px] += sz[py] else: p[px] = py c += sz[px] * sz[py] sz[py] += sz[px] return 1 k = 0 ans = [0]*M for w, u, v in E: print(c, w, u, v) while k < len(Q) and Q[k] < w: e = Q[k] for i in MP[e]: ans[i] = c k += 1 unite(u, v) while k < len(Q): e = Q[k] for i in MP[e]: ans[i] = c k += 1 print(*ans) ```
instruction
0
49,751
13
99,502
No
output
1
49,751
13
99,503
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Guy-Manuel and Thomas are planning 144 trips around the world. You are given a simple weighted undirected connected graph with n vertexes and m edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 3 which passes through the vertex 1. The cost of a path (not necessarily simple) in this graph is defined as the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges in that path with each edge being counted as many times as the path passes through it. But the trips with cost 0 aren't exciting. You may choose any subset of edges incident to the vertex 1 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 0 which passes through the vertex 1 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 10^9+7. Input The first line contains two integers n and m (1 ≀ n,m ≀ 10^5) β€” the number of vertexes and edges in the graph. The i-th of the next m lines contains three integers a_i, b_i and w_i (1 ≀ a_i, b_i ≀ n, a_i β‰  b_i, 0 ≀ w_i < 32) β€” the endpoints of the i-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 3 which passes through the vertex 1. Output Output the answer modulo 10^9+7. Examples Input 6 8 1 2 0 2 3 1 2 4 3 2 6 2 3 4 8 3 5 4 5 4 5 5 6 6 Output 2 Input 7 9 1 2 0 1 3 1 2 3 9 2 4 3 2 5 4 4 5 7 3 6 6 3 7 7 6 7 8 Output 1 Input 4 4 1 2 27 1 3 1 1 4 1 3 4 0 Output 6 Note The pictures below represent the graphs from examples. <image> In the first example, there aren't any nontrivial cycles with cost 0, so we can either remove or keep the only edge incident to the vertex 1. <image> In the second example, if we don't remove the edge 1-2, then there is a cycle 1-2-4-5-2-1 with cost 0; also if we don't remove the edge 1-3, then there is a cycle 1-3-2-4-5-2-3-1 of cost 0. The only valid subset consists of both edges. <image> In the third example, all subsets are valid except for those two in which both edges 1-3 and 1-4 are kept. Submitted Solution: ``` from functools import lru_cache from collections import defaultdict @lru_cache(None) def merge(a, b): if a is 1 or b is 1 or a & b: return 1 ret = a | b for i in range(1, 32): for j in range(1, 32): if (a >> i) & (b >> j) & 1: ret |= 1 << (i ^ j) return ret def find(a): if a == par[a]: return a p = find(par[a]) wt[a] ^= wt[par[a]] par[a] = p return p def join(a, b, c): pa, pb = find(a), find(b) if pa != pb: if sz[a] < sz[b]: a, b = b, a sz[a] += sz[b] par[b] = a wt[b] = c wts[a] = merge(wts[a], wts[b]) else: newcyc = wt[a] ^ wt[b] ^ c wts[pa] = merge(wts[pa], 1 << newcyc) N, M = map(int, input().strip().split()) P = int(1e9 + 7) adj1 = {} edges = [] for _ in range(M): a, b, c = map(int, input().strip().split()) if a == 1: adj1[b - 1] = c elif b == 1: adj1[a - 1] = c else: edges.append((a - 1, b - 1, c)) sz = [1] * N par = [*range(N)] wt = [0] * N wts = [0] * N a1e = {} for a, b, c in edges: if a in adj1 and b in adj1: cyc = adj1[a] ^ adj1[b] ^ c a1e[a] = (b, c) a1e[b] = (a, c) else: join(a, b, c) dp = {0 : 1} for a in adj1: new_dp = defaultdict(int) new_dp.update(dp) if a in a1e: b, c = a1e[a] if a > b: continue space1 = merge(wts[par[a]], wts[par[b]]) to_merge = [space1, space1, merge(space1, 1 << c)] else: to_merge = [wts[par[a]]] for new_space in to_merge: for space, cnt in dp.items(): new_dp[merge(space, new_space)] += cnt dp = {space : cnt % P for space, cnt in new_dp.items() if space is not 1} print(sum(dp.values()) % P) ```
instruction
0
49,800
13
99,600
No
output
1
49,800
13
99,601
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Guy-Manuel and Thomas are planning 144 trips around the world. You are given a simple weighted undirected connected graph with n vertexes and m edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 3 which passes through the vertex 1. The cost of a path (not necessarily simple) in this graph is defined as the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges in that path with each edge being counted as many times as the path passes through it. But the trips with cost 0 aren't exciting. You may choose any subset of edges incident to the vertex 1 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 0 which passes through the vertex 1 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 10^9+7. Input The first line contains two integers n and m (1 ≀ n,m ≀ 10^5) β€” the number of vertexes and edges in the graph. The i-th of the next m lines contains three integers a_i, b_i and w_i (1 ≀ a_i, b_i ≀ n, a_i β‰  b_i, 0 ≀ w_i < 32) β€” the endpoints of the i-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 3 which passes through the vertex 1. Output Output the answer modulo 10^9+7. Examples Input 6 8 1 2 0 2 3 1 2 4 3 2 6 2 3 4 8 3 5 4 5 4 5 5 6 6 Output 2 Input 7 9 1 2 0 1 3 1 2 3 9 2 4 3 2 5 4 4 5 7 3 6 6 3 7 7 6 7 8 Output 1 Input 4 4 1 2 27 1 3 1 1 4 1 3 4 0 Output 6 Note The pictures below represent the graphs from examples. <image> In the first example, there aren't any nontrivial cycles with cost 0, so we can either remove or keep the only edge incident to the vertex 1. <image> In the second example, if we don't remove the edge 1-2, then there is a cycle 1-2-4-5-2-1 with cost 0; also if we don't remove the edge 1-3, then there is a cycle 1-3-2-4-5-2-3-1 of cost 0. The only valid subset consists of both edges. <image> In the third example, all subsets are valid except for those two in which both edges 1-3 and 1-4 are kept. Submitted Solution: ``` from functools import lru_cache from collections import defaultdict @lru_cache(None) def merge(a, b): if a is 1 or b is 1 or a & b: return 1 ret = a | b for i in range(1, 32): for j in range(1, 32): if (a >> i) & (b >> j) & 1: ret |= 1 << (i ^ j) return ret def find(a): if a == par[a]: return a p = find(par[a]) wt[a] ^= wt[par[a]] par[a] = p return p def join(a, b, c): pa, pb = find(a), find(b) if pa != pb: if sz[a] < sz[b]: a, b = b, a sz[a] += sz[b] par[b] = a wt[b] = c wts[a] = merge(wts[a], wts[b]) else: newcyc = wt[a] ^ wt[b] ^ c wts[pa] = merge(wts[pa], 1 << newcyc) N, M = map(int, input().strip().split()) P = int(1e9 + 7) adj1 = {} edges = [] for _ in range(M): a, b, c = map(int, input().strip().split()) if a == 1: adj1[b - 1] = c elif b == 1: adj1[a - 1] = c else: edges.append((a - 1, b - 1, c)) sz = [1] * N par = [*range(N)] wt = [0] * N wts = [0] * N a1e = {} for a, b, c in edges: if a in adj1 and b in adj1: cyc = adj1[a] ^ adj1[b] ^ c a1e[a] = (b, c) a1e[b] = (a, c) else: join(a, b, c) dp = {0 : 1} for a in adj1: new_dp = defaultdict(int) new_dp.update(dp) if a in a1e: b, c = a1e[a] if a > b: continue to_merge = [wts[par[a]], wts[par[b]], merge(merge(wts[par[a]], wts[par[b]]), 1 << c)] else: to_merge = [wts[par[a]]] for new_space in to_merge: for space, cnt in dp.items(): new_dp[merge(space, new_space)] += cnt dp = {space : cnt % P for space, cnt in new_dp.items() if space is not 1} print(sum(dp.values()) % P) ```
instruction
0
49,801
13
99,602
No
output
1
49,801
13
99,603
Provide tags and a correct Python 3 solution for this coding contest problem. You are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself). Input The first line of the input contains two integers n and m (1 ≀ n ≀ 15, 0 ≀ m ≀ 2000), n is the amount of vertices, and m is the amount of edges. Following m lines contain edges as a triples x, y, w (1 ≀ x, y ≀ n, 1 ≀ w ≀ 10000), x, y are edge endpoints, and w is the edge length. Output Output minimal cycle length or -1 if it doesn't exists. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 3 Input 3 2 1 2 3 2 3 4 Output 14
instruction
0
49,938
13
99,876
Tags: bitmasks, graph matchings, graphs Correct Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc @bootstrap def optimal_path(curr): global res global best if curr==[]: res=min(res,best) yield last=curr.pop() i = 0 while i < len(curr): req = curr.pop(i) best += adj[req][last] yield optimal_path(curr) best -= adj[req][last] curr.insert(i, req) i += 1 curr.append(last) yield n,m=map(int,input().split()) adj=[[float("inf") for i in range(n+1)] for j in range(n+1)] for i in range(1,n+1): adj[i][i]=0 deg=[0]*(n+1) tot=0 for j in range(m): u,v,w=map(int,input().split()) tot+=w adj[u][v]=min(adj[u][v],w) adj[v][u]=min(adj[v][u],w) deg[u]+=1 deg[v]+=1 #Floyd Warshall for i in range(1,n+1): for j in range(1,n+1): for k in range(1,n+1): adj[j][k]=min(adj[j][k],adj[j][i]+adj[i][k]) poss=1 for i in range(1,n+1): if deg[i]>0 and adj[1][i]==float("inf"): poss=0 break if not poss: print(-1) else: oddver=[] for i in range(1,n+1): if deg[i]%2: oddver.append(i) res=float("inf") best=0 optimal_path(oddver) print(tot+res) ```
output
1
49,938
13
99,877
Provide tags and a correct Python 3 solution for this coding contest problem. You are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself). Input The first line of the input contains two integers n and m (1 ≀ n ≀ 15, 0 ≀ m ≀ 2000), n is the amount of vertices, and m is the amount of edges. Following m lines contain edges as a triples x, y, w (1 ≀ x, y ≀ n, 1 ≀ w ≀ 10000), x, y are edge endpoints, and w is the edge length. Output Output minimal cycle length or -1 if it doesn't exists. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 3 Input 3 2 1 2 3 2 3 4 Output 14
instruction
0
49,939
13
99,878
Tags: bitmasks, graph matchings, graphs Correct Solution: ``` import math N = 15 mat = 0 inf = 1000000000 answer = inf def Get_Cycle_Length(v,graph): global mat global answer if len(v) == 0: #por lo de conf 3 answer = min(answer,mat) return end = v.pop() i = 0 while i<len(v): se = v.pop(i) mat += graph[se][end] Get_Cycle_Length(v,graph) mat -= graph[se][end] v.insert(i,se) i+=1 v.append(end) def main(): n,m = map(int,input().split()) graph = [[inf] * n for i in range(n)] deg = [0] * n sum = 0 for i in range(n): graph[i][i] = 0 for i in range(m): x,y,w = map(int,input().split()) x -= 1 y -= 1 deg[x]+=1 deg[y]+=1 graph[x][y] = min(graph[x][y],w) graph[y][x] = min(graph[y][x],w) sum += w for i in range(n): for j in range(n): # aqui veo si hay algun camino de menos peso for k in range(n): graph[j][k] = min(graph[j][k],graph[j][i] + graph[i][k]) for i in range(n): if graph[0][i] == inf and deg[i] > 0: print('-1') return v = [] for i in range(n): if deg[i] % 2 != 0: v.append(i) Get_Cycle_Length(v,graph) print(sum + answer) main() ```
output
1
49,939
13
99,879
Provide tags and a correct Python 3 solution for this coding contest problem. You are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself). Input The first line of the input contains two integers n and m (1 ≀ n ≀ 15, 0 ≀ m ≀ 2000), n is the amount of vertices, and m is the amount of edges. Following m lines contain edges as a triples x, y, w (1 ≀ x, y ≀ n, 1 ≀ w ≀ 10000), x, y are edge endpoints, and w is the edge length. Output Output minimal cycle length or -1 if it doesn't exists. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 3 Input 3 2 1 2 3 2 3 4 Output 14
instruction
0
49,940
13
99,880
Tags: bitmasks, graph matchings, graphs Correct Solution: ``` import math N = 15 mat = 0 inf = 1000000000 answer = inf def Get_Cycle_Length(v,graph): global mat global answer if len(v) == 0: answer = min(answer,mat) return end = v.pop() i = 0 while i<len(v): se = v.pop(i) mat += graph[se][end] Get_Cycle_Length(v,graph) mat -= graph[se][end] v.insert(i,se) i+=1 v.append(end) def main(): n,m = map(int,input().split()) graph = [[inf] * n for i in range(n)] deg = [0] * n sum = 0 for i in range(n): graph[i][i] = 0 for i in range(m): x,y,w = map(int,input().split()) x -= 1 y -= 1 deg[x]+=1 deg[y]+=1 graph[x][y] = min(graph[x][y],w) graph[y][x] = min(graph[y][x],w) sum += w for i in range(n): for j in range(n): # aqui veo si hay algun camino de menos peso for k in range(n): graph[j][k] = min(graph[j][k],graph[j][i] + graph[i][k]) for i in range(n): if graph[0][i] == inf and deg[i] > 0: print('-1') return v = [] for i in range(n): if deg[i] % 2 != 0: v.append(i) #if len(v) == n: #por lo de conf 3 # print(sum) # return Get_Cycle_Length(v,graph) print(sum + answer) main() ```
output
1
49,940
13
99,881
Provide tags and a correct Python 3 solution for this coding contest problem. You are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself). Input The first line of the input contains two integers n and m (1 ≀ n ≀ 15, 0 ≀ m ≀ 2000), n is the amount of vertices, and m is the amount of edges. Following m lines contain edges as a triples x, y, w (1 ≀ x, y ≀ n, 1 ≀ w ≀ 10000), x, y are edge endpoints, and w is the edge length. Output Output minimal cycle length or -1 if it doesn't exists. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 3 Input 3 2 1 2 3 2 3 4 Output 14
instruction
0
49,941
13
99,882
Tags: bitmasks, graph matchings, graphs Correct Solution: ``` import math N = 15 mat = 0 inf = 1000000000 answer = inf def Get_Cycle_Length(v,graph): global mat global answer if len(v) == 0: #por lo de conf 3 answer = min(answer,mat) return end = v.pop() i = 0 while i<len(v): se = v.pop(i) mat += graph[se][end] Get_Cycle_Length(v,graph) mat -= graph[se][end] v.insert(i,se) i+=1 v.append(end) def main(): n,m = map(int,input().split()) graph = [[inf] * n for i in range(n)] deg = [0] * n sum = 0 for i in range(n): graph[i][i] = 0 for i in range(m): x,y,w = map(int,input().split()) x -= 1 y -= 1 deg[x]+=1 deg[y]+=1 graph[x][y] = min(graph[x][y],w) graph[y][x] = min(graph[y][x],w) sum += w for k in range(n): for i in range(n): # aqui veo si hay algun camino de menos peso for j in range(n): graph[i][j] = min(graph[i][j],graph[i][k] + graph[k ][j]) for i in range(n): if graph[0][i] == inf and deg[i] > 0: print('-1') return v = [] for i in range(n): if deg[i] % 2 != 0: v.append(i) Get_Cycle_Length(v,graph) print(sum + answer) main() ```
output
1
49,941
13
99,883
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself). Input The first line of the input contains two integers n and m (1 ≀ n ≀ 15, 0 ≀ m ≀ 2000), n is the amount of vertices, and m is the amount of edges. Following m lines contain edges as a triples x, y, w (1 ≀ x, y ≀ n, 1 ≀ w ≀ 10000), x, y are edge endpoints, and w is the edge length. Output Output minimal cycle length or -1 if it doesn't exists. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 3 Input 3 2 1 2 3 2 3 4 Output 14 Submitted Solution: ``` import math N = 15 mat = 0 inf = 1000000000 answer = inf def Get_Cycle_Length(v,graph): global mat global answer if len(v) == 0: answer = min(answer,mat) return end = v[-1] del(v[-1]) i = 0 while i<len(v): se = v[i] del(v[i]) mat += graph[se][end] Get_Cycle_Length(v,graph) mat -= graph[se][end] v.insert(i,se) i+=1 def main(): n,m = map(int,input().split()) graph = [[inf] * n for i in range(n)] deg = [0] * n sum = 0 for i in range(n): graph[i][i] = 0 for i in range(m): x,y,w = map(int,input().split()) x -= 1 y -= 1 deg[x]+=1 deg[y]+=1 graph[x][y] = min(graph[x][y],w) graph[y][x] = min(graph[y][x],w) sum += w for i in range(n): for j in range(n): # aqui veo si hay algun camino de menos peso for k in range(n): graph[j][k] = min(graph[j][k],graph[j][i] + graph[i][k]) for i in range(n): if graph[0][i] == inf and deg[i] > 0: print('-1') return v = [] for i in range(n): if deg[i] % 2 != 0: v.append(i) #if len(v) == n: #por lo de conf 3 # print(sum) # return Get_Cycle_Length(v,graph) print(sum + answer) main() ```
instruction
0
49,942
13
99,884
No
output
1
49,942
13
99,885
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself). Input The first line of the input contains two integers n and m (1 ≀ n ≀ 15, 0 ≀ m ≀ 2000), n is the amount of vertices, and m is the amount of edges. Following m lines contain edges as a triples x, y, w (1 ≀ x, y ≀ n, 1 ≀ w ≀ 10000), x, y are edge endpoints, and w is the edge length. Output Output minimal cycle length or -1 if it doesn't exists. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 3 Input 3 2 1 2 3 2 3 4 Output 14 Submitted Solution: ``` import math N = 15 mat = 0 inf = 1000000000 answer = inf def Get_Cycle_Length(v,graph): global mat global answer if len(v) == 0: #por lo de conf 3 answer = min(answer,mat) return end = v.pop() i = 0 while i<len(v): se = v.pop(i) mat += graph[se][end] Get_Cycle_Length(v,graph) mat -= graph[se][end] v.insert(i,se) i+=1 v.append(end) def main(): n,m = map(int,input().split()) graph = [[inf] * n for i in range(n)] deg = [0] * n sum = 0 for i in range(n): graph[i][i] = 0 for i in range(m): x,y,w = map(int,input().split()) x -= 1 y -= 1 deg[x]+=1 deg[y]+=1 graph[x][y] = min(graph[x][y],w) graph[y][x] = min(graph[y][x],w) sum += w for i in range(n): for j in range(n): # aqui veo si hay algun camino de menos peso for k in range(n): graph[j][k] = min(graph[j][k],graph[j][i] + graph[i][k]) for i in range(n): if graph[0][i] == inf and deg[i] >= 0: print('-1') return v = [] for i in range(n): if deg[i] % 2 != 0: v.append(i) Get_Cycle_Length(v,graph) print(sum + answer) main() ```
instruction
0
49,943
13
99,886
No
output
1
49,943
13
99,887
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
50,078
13
100,156
Tags: constructive algorithms, graphs Correct Solution: ``` n, m = [int(x) for x in input().split()] connections = [[i != j for j in range(n)] for i in range(n)] cnt = [0] * n for _ in range(m): u, v = [int(x) - 1 for x in input().split()] connections[u][v] = connections[v][u] = False cnt[u] += 1 cnt[v] += 1 #print('\n'.join(''.join(str(int(y)) for y in x) for x in connections)) s = [''] * n for i, c in enumerate(cnt): if c == n - 1: s[i] = 'b' def traverse(vertex, letter): # print(vertex + 1, letter) s[vertex] = letter for i, connection in enumerate(connections[vertex]): if connection: if s[i] == '': if not traverse(i, 'c' if letter == 'a' else 'a'): return False elif s[i] == letter: return False return True possibility = True for i in range(n): if s[i] == '': possibility = traverse(i, 'a') break for i, c in enumerate(s): for j in range(n): if connections[i][j] != ((s[i] == 'a' and s[j] == 'c') or (s[i] == 'c' and s[j] == 'a')): possibility = False break if possibility: print('Yes', ''.join(s), sep='\n') else: print('No') ```
output
1
50,078
13
100,157
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
50,079
13
100,158
Tags: constructive algorithms, graphs Correct Solution: ``` n, m = map(int, input().split(' ')) G = [[0]*n for i in range(n)] for i in range(m): u, v = map(lambda x:int(x)-1, input().split(' ')) G[u][v] = G[v][u] = 1 s = [' ']*n for i in range(n): if G[i].count(1) == n-1: s[i] = 'b' try: anode = s.index(' ') s[anode] = 'a' except: print('Yes') print(''.join(s)) exit() for i in range(n): if s[i] == ' ' and G[anode][i] == 1: s[i] = 'a' elif s[i] == ' ' and G[anode][i] == 0: s[i] = 'c' for i in range(n): for j in range(i+1, n): if (s[i] != s[j] and s[i] != 'b' and s[j] != 'b') == G[i][j]: print('No') exit() print('Yes') print(''.join(s)) ```
output
1
50,079
13
100,159
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
50,080
13
100,160
Tags: constructive algorithms, graphs Correct Solution: ``` import sys n, m = map(int, input().split()) graph = [set([i]) for i in range(n)] for i in range(m): i, j = map(int, input().split()) graph[i - 1].add(j - 1) graph[j - 1].add(i - 1) thebs = set() for i in range(n): if len(graph[i]) == n: thebs.add(i) aset = False cset = False theas = set() thecs = set() flag = True for i in range(n): if i in thebs: pass elif aset == False: aset = graph[i] theas.add(i) elif graph[i] == aset: theas.add(i) elif cset == False: cset = graph[i] thecs.add(i) elif graph[i] == cset: thecs.add(i) else: print("No") flag = False break if flag: print("Yes") for i in range(n): if i in theas: print("a", end='') elif i in thebs: print("b", end='') elif i in thecs: print("c", end='') ```
output
1
50,080
13
100,161
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
50,081
13
100,162
Tags: constructive algorithms, graphs Correct Solution: ``` from pprint import pprint def main(): n, m = map(int, input().split(" ")) adj = [[1] * n for _ in range(n)] for i in range(n): adj[i][i] = 0 for _ in range(m): x, y = map(int, input().split(" ")) x -= 1 y -= 1 adj[x][y] = adj[y][x] = 0 adj = [tuple(r) for r in adj] reps = sorted({tuple([0]*n), *adj}) if len(reps) == 1: print("Yes") print("a"*n) return elif len(reps) == 3: gs = [[0]*n for _ in range(3)] for i, r in enumerate(adj): ri = reps.index(r) gs[ri][i] = 1 if ri else 0 gs = [tuple(g) for g in gs] for i, r in enumerate(adj): if r != gs[[0, 2, 1][reps.index(r)]]: print("No") return print("Yes") print("".join("bac"[reps.index(r)] for r in adj)) return print("No") if __name__ == '__main__': main() """ 4 4 1 2 2 3 1 3 2 4 """ ```
output
1
50,081
13
100,163
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
50,082
13
100,164
Tags: constructive algorithms, graphs Correct Solution: ``` n,m = map(int,input().split()) g = [set() for i in range(n)] for i in range(m): a = tuple(map(int,input().split())) g[a[0]-1].add(a[1]-1) g[a[1]-1].add(a[0]-1) res = ['']*n good = 1 for i in range(n): if len(g[i]) == n-1: res[i] = 'b' a = 0 c = 0 for i in range(n): if a and res[i] == '': res[i] = 'c' if not a and res[i] == '': a = 1 res[i] = 'a' if res[i] == 'a': for elem in g[i]: if res[elem] == 'c': good = 0 if res[elem] == '': res[elem] = 'a' if res[i] == 'c': for elem in g[i]: if res[elem] == 'a': good = 0 if res[elem] == '': res[elem] = 'c' if '' in res: good = 0 for i in range(n): for j in range(i+1,n): if res[j] == res[i]: if j not in g[i]: good = 0 if good : print('YES') print(''.join(res)) else: print('NO') ```
output
1
50,082
13
100,165
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
50,083
13
100,166
Tags: constructive algorithms, graphs Correct Solution: ``` from math import * N, M = 510, 3 * 10 ** 5 + 10 g = [[] for _ in range(M)] n , m = map(int, input().split()) mx = [[False] * N for _ in range(N + 1)] for _ in range(m): u, v = map(int, input().split()) mx[u][v] = mx[v][u] = True all_eq = True mark = [False] * N for i in range(1, n + 1): for j in range(i + 1, n + 1): if not mx[i][j]: all_eq = False mark[i] = True g[i].append(j) g[j].append(i) if all_eq: print("YES") print(n * 'a') exit(0) ans = [-1] * N def dfs(v, c): ans[v] = c res = False for u in g[v]: if ans[u] == -1: res |= dfs(u, 2 - c) elif ans[u] == ans[v]: return False return res for i in range(1, n + 1): if mark[i] and ans[i] == -1 and dfs(i, 0): print("NO") exit(0) for i in range(1, n + 1): if len(g[i]) == 0: ans[i] = 1 if ans[i] == -1: print("NO") exit(0) for i in range(1, n + 1): for j in range(i + 1, n + 1): if mx[i][j] != (abs(ans[i] - ans[j]) != 2): print("NO") exit(0) print("YES") for i in range(1, n + 1): print(chr(ans[i] + ord('a')), end = '') print() ```
output
1
50,083
13
100,167
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
50,084
13
100,168
Tags: constructive algorithms, graphs Correct Solution: ``` def dfs(v, graph, used, str_arr, color=0): used[v] = True str_arr[v] = color for u in graph[v]: if used[u] and str_arr[u] == color: return False if not used[u] and not dfs(u, graph, used, str_arr, color ^ 1): return False return True def main(): n, m = list(map(int, input().strip().split())) graph_adj = [[0] * n for i in range(n)] for i in range(m): a, b = list(map(int, input().strip().split())) a -= 1 b -= 1 graph_adj[a][b] = 1 graph_adj[b][a] = 1 arr_adj = [[] for i in range(n)] for i in range(n): for j in range(i + 1, n): if graph_adj[i][j] == 0: arr_adj[i].append(j) arr_adj[j].append(i) used = [False] * n str_arr = [-1] * n #print(arr_adj) for i in range(n): if not used[i] and len(arr_adj[i]) > 0: if not dfs(i, arr_adj, used, str_arr): print("No") return #print(str_arr) for i in range(n): if str_arr[i] == -1: str_arr[i] = 'b' elif str_arr[i] == 0: str_arr[i] = 'a' else: str_arr[i] = 'c' for i in range(n): for j in range(i + 1, n): if graph_adj[i][j] and (str_arr[i] == 'a' and str_arr[j] == 'c' or str_arr[i] == 'c' and str_arr[j] == 'a'): print("No") return print("Yes") print(''.join(str_arr)) main() ```
output
1
50,084
13
100,169
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
50,085
13
100,170
Tags: constructive algorithms, graphs Correct Solution: ``` from sys import stdin n,m = [int(x) for x in stdin.readline().split()] graph = [set([y for y in range(n)]) for x in range(n)] graph2 = [set() for x in range(n)] for x in range(n): graph[x].remove(x) for edge in range(m): a,b = [int(x) for x in stdin.readline().split()] a -= 1 b -= 1 graph[a].remove(b) graph[b].remove(a) graph2[a].add(b) graph2[b].add(a) notVisited = set([x for x in range(n)]) val = [-1 for x in range(n)] for x in range(n): if not graph[x]: val[x] = 'b' notVisited.remove(x) valid = True while notVisited: for x in notVisited: q = [(x,'a')] break cur = 0 while q: nxt,char = q.pop() if char == 'a': antC = 'c' else: antC = 'a' if nxt in notVisited: notVisited.remove(nxt) val[nxt] = char for x in graph[nxt]: if x in notVisited: q.append((x,antC)) else: if val[x] == char: valid = False break for x in graph2[nxt]: if val[x] == antC: valid = False if valid: print('Yes') print(''.join(val)) else: print('No') ```
output
1
50,085
13
100,171
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` #filename 623A Codeforce AIM Tech Round (Div. 1) n, m = input().split() n = int(n) m = int(m) a = n * [False] for i in range(0,n): a[i] = n * [False] s = n * ['0'] adj = n * [0] for i in range(0,m): u, v = input().split() u = int(u)-1 v = int(v)-1 a[u][v] = True a[v][u] = True adj[u] += 1 adj[v] += 1 def dfs(u): #print(u) global res if adj[u] == n - 1: s[u] = 'b' return if s[u] == 'a': change = 'c' else: change = 'a' s[u] = 'c' for i in range(0,n): if not a[u][i] and i != u: if s[i] == s[u]: res = 'No' return else: s[i] = change #print(i) else: if i != u and s[i] == change: res = 'No' res = 'Yes' for i in range(0,n): if res == 'Yes': dfs(i) print(res) if res == 'Yes': for i in s: print(i,end= "") ```
instruction
0
50,086
13
100,172
Yes
output
1
50,086
13
100,173
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` Read = lambda:map(int, input().split()) from functools import reduce def init(): g = [[False] * (n + 1) for _ in range(n + 1)] for _ in range(m): x, y = Read() g[x][y] = g[y][x] = True return g def solve(): if n == 1 and m == 0: return 'Yes\n' + 'a' color = [0 for _ in range(n+1)] g = init() for i in range(1, n + 1): if reduce(lambda x, y : x and y, g[i][1:i] + g[i][i + 1:]): color[i] = 2 # 'b' for u in range(1, n + 1): if not color[u]: color[u] = 1 # 'a' for v in range(1, n + 1): if u != v and g[u][v] and not color[v]: color[v] = 1 break for i in range(1, n + 1): for j in range(1, n + 1): if i == j: continue if g[i][j] and color[i] + color[j] == 1: return 'No' if not g[i][j] and color[i] == color[j]: return 'No' def judge(x): if x == 1: return 'a' elif x == 2: return 'b' else: return 'c' return 'Yes\n' + ''.join(map(judge, color[1:])) if __name__ == '__main__': while True: try: n, m = Read() except: break print(solve()) ```
instruction
0
50,087
13
100,174
Yes
output
1
50,087
13
100,175
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` #!/usr/bin/python3 (n, m) = tuple(map(int, input().split())) cnt = [0]*n edges = [] for i in range(m): (u, v) = tuple(map(int, input().split())) edges.append((u, v)) cnt[u-1] += 1 cnt[v-1] += 1 edges = sorted(edges) edge_set = set(edges) A = set() B = set() C = set() for i in range(n): if cnt[i] == n-1: B.add(i+1) else: in_A = True in_C = True for a in A: if ((a, i+1) not in edge_set and (i+1, a) not in edge_set): in_A = False else: in_C = False for c in C: if ((c, i+1) not in edge_set and (i+1, c) not in edge_set): in_C = False else: in_A = False if in_A == True and in_C == True: C.add(i+1) elif in_A == False and in_C == True: C.add(i+1) elif in_A == True and in_C == False: A.add(i+1) else: print("No") break else: print("Yes") ans = "" for i in range(1, n+1): if i in A: ans += 'a' if i in B: ans += 'b' if i in C: ans += 'c' print(ans) ```
instruction
0
50,088
13
100,176
Yes
output
1
50,088
13
100,177
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` def dfs(v): visit[v] = cnt for u in vertex[v]: if not visit[u] and u in challengers: dfs(u) n, m = map(int, input().split()) vertex = [[] for i in range(n + 1)] challengers = set() ans = [''] * (n + 1) middle = set() for i in range(m): a, b = map(int, input().split()) vertex[a].append(b) vertex[b].append(a) for i in range(1, n + 1): s = set(j for j in range(1, n + 1)) s.discard(i) if s == set(vertex[i]): ans[i] = 'b' middle.add(i) else: challengers.add(i) visit = [0] * (n + 1) cnt = 0 for c in challengers: if not visit[c]: cnt += 1 dfs(c) if cnt > 2 or cnt == 1: print('No') elif cnt == 2: first = set() second = set() for i in range(1, n + 1): if visit[i] == 1: first.add(i) elif visit[i] == 2: second.add(i) for c in first: s = first s.discard(c) if set(vertex[c]) - middle != s: print('No') break s.add(c) else: for c in first: ans[c] = 'a' for c in second: s = second s.discard(c) if set(vertex[c]) - middle != s: print('No') break s.add(c) else: for c in second: ans[c] = 'c' if not ans[1:].count(''): print('Yes', ''.join(ans[1:]), sep = '\n') ```
instruction
0
50,089
13
100,178
Yes
output
1
50,089
13
100,179
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` from sys import stdin, stdout from collections import Counter, defaultdict from itertools import permutations, combinations raw_input = stdin.readline pr = stdout.write def in_arr(): return map(int,raw_input().split()) def pr_num(n): stdout.write(str(n)+'\n') def pr_arr(arr): pr(' '.join(map(str,arr))+'\n') range = xrange # not for python 3.0+ # main code n,m=in_arr() deg=[0]*n x,y,z=0,0,0 ans=['a']*n adj=defaultdict(Counter) for i in range(m): u,v=in_arr() deg[u-1]+=1 deg[v-1]+=1 adj[u-1][v-1]=1 adj[v-1][u-1]=1 for i in range(n): if deg[i]==n-1: y+=1 ans[i]='b' for i in range(n): if ans[i]=='a': ans[i]='c' for j in range(n): if adj[i][j] and ans[j]!='b': ans[j]='c' break f=0 for i in range(n): for j in range(i+1,n): if (adj[i][j]^int(abs(ord(ans[j])-ord(ans[i]))<=1)): f=1 break if f: break if f: pr('No') else: pr('Yes\n') pr(''.join(ans)) ```
instruction
0
50,090
13
100,180
Yes
output
1
50,090
13
100,181
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` n,m = map(int,input().split()) g = [set() for i in range(n)] for i in range(m): a = tuple(map(int,input().split())) g[a[0]-1].add(a[1]-1) g[a[1]-1].add(a[0]-1) res = ['']*n good = 1 for i in range(n): if len(g[i]) == n-1: res[i] = 'b' a = 0 c = 0 for i in range(n): if a and res[i] == '': res[i] = 'c' if not a and res[i] == '': a = 1 res[i] = 'a' if res[i] == 'a': for elem in g[i]: if res[elem] == 'c': good = 0 if res[i] == 'c': for elem in g[i]: if res[elem] == 'a': good = 0 if '' in res: good = 0 for i in range(n): for j in range(n): if i == j:continue if res[i] == res[j]: if j not in g[i]: good = 0 if good : print('YES') print(''.join(res)) else: print('NO') ```
instruction
0
50,091
13
100,182
No
output
1
50,091
13
100,183
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` from sys import stdin n,m = [int(x) for x in stdin.readline().split()] graph = [set([y for y in range(n)]) for x in range(n)] for x in range(n): graph[x].remove(x) for edge in range(m): a,b = [int(x) for x in stdin.readline().split()] a -= 1 b -= 1 graph[a].remove(b) graph[b].remove(a) notVisited = set([x for x in range(n)]) val = [-1 for x in range(n)] for x in range(n): if not graph[x]: val[x] = 'b' notVisited.remove(x) valid = True while notVisited: for x in notVisited: q = [(x,'a')] break cur = 0 while q: nxt,char = q.pop() if nxt in notVisited: notVisited.remove(nxt) val[nxt] = char for x in graph[nxt]: if x in notVisited: if char == 'a': q.append((x,'c')) else: q.append((x,'a')) else: if val[x] == char: valid = False break if valid: print('Yes') print(''.join(val)) else: print('No') ```
instruction
0
50,092
13
100,184
No
output
1
50,092
13
100,185
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` from collections import defaultdict n, m = map(int, input("").split()) edge_list =defaultdict(list) for i in range(m): start, end = map(int, input("").split()) edge_list[start].append(end) edge_list[end].append(start) set_b = set() for vertice in edge_list: if len(edge_list[vertice]) == n-1: set_b.add(vertice) a_ver = None for vertice in edge_list: if vertice not in set_b: a_ver = vertice break def dfs(vertice, visited, set_a, set_b): if vertice in visited: return if vertice in set_b: return else: visited.add(vertice) set_a.add(vertice) for child in edge_list[vertice]: if child not in visited: dfs(child, visited, set_a, set_b) def is_connected(set_type, connected_set): for vertice in set_type: for connected_vertice in connected_set: if connected_vertice != vertice and connected_vertice not in edge_list[vertice]: return False return True if a_ver: visited = set() set_a = set() dfs(a_ver,visited, set_a, set_b) set_c = set(i for i in range(1, n+1))-set_b-set_a is_connected_a = is_connected(set_a, set_a.union(set_b)) is_connected_c = is_connected(set_c, set_c.union(set_b)) if is_connected_a and is_connected_c: constructed_string = ['a'if i in set_a else 'c' if i in set_c else 'b' for i in range(1, n+1)] print('Yes') print("".join(map(str,constructed_string))) else: print('No') elif len(set_b) == n: constructed_string = ['a' for i in range(n)] print('Yes') print("".join(map(str,constructed_string))) elif n == 1: print('Yes') print('a') ```
instruction
0
50,093
13
100,186
No
output
1
50,093
13
100,187
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i β‰  j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> β€” the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` import collections n, m = map(int, input().split()) ans, A, B, C = [''] * n, [], [], [] d = collections.defaultdict(list) for i in range(m): x, y = map(int, input().split()) d[y - 1].append(x - 1) d[x - 1].append(y - 1) for k, v in d.items(): #set 'b' if len(v) == n - 1: ans[k] = 'b' B.append(k) for i in range(n): #set 'a' if ans[i] == '': ans[i] = 'a' A.append(i) de = collections.deque() de.append(i) while(len(de) != 0): cur = de.popleft() for j in d[cur]: if ans[j] == '': ans[j] = 'a' A.append(j) de.append(j) break for i in range(n): #set 'c' if ans[i] == '': ans[i] = 'c' C.append(i) #print(A.sort(), B.sort(), C.sort()) if len(C) > 0: if len(C) > 1: B.extend(C[1:]) if sum(B) != sum(d[C[0]]): print('No') exit(0) print('Yes') print(''.join(ans)) ```
instruction
0
50,094
13
100,188
No
output
1
50,094
13
100,189
Provide tags and a correct Python 3 solution for this coding contest problem. Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≀ a ≀ b ≀ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph. When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots. How many dominoes at most can Anadi place on the edges of his graph? Input The first line contains two integers n and m (1 ≀ n ≀ 7, 0 ≀ m ≀ (nβ‹…(n-1))/(2)) β€” the number of vertices and the number of edges in the graph. The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≀ a, b ≀ n, a β‰  b) and denote that there is an edge which connects vertices a_i and b_i. The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices. Output Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 4 Input 7 0 Output 0 Input 3 1 1 3 Output 1 Input 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 Output 16 Note Here is an illustration of Anadi's graph from the first sample test: <image> And here is one of the ways to place a domino on each of its edges: <image> Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
instruction
0
50,586
13
101,172
Tags: brute force, graphs Correct Solution: ``` '''input 4 4 1 2 2 3 3 4 4 1 ''' from sys import stdin from collections import defaultdict from itertools import combinations def change_graph(define): temp = defaultdict(list) for i in graph: for node in graph[i]: temp[define[i]].append(define[node]) return temp def make(first, second): if first > second: first, second = second, first return str(first) + ' ' + str(second) def check(arr): # print(arr) global ans define = dict() j = 0 for i in graph: define[i] = arr[j] j += 1 temp_graph = change_graph(define) visited = dict() for i in range(1, 7): for j in range(i, 7): visited[make(i, j)] = False t = 0 for i in temp_graph: for node in temp_graph[i]: if visited[make(i, node)] == False: visited[make(i, node)] = True t += 1 ans = max(t, ans) # main starts n, m = list(map(int, stdin.readline().split())) graph = defaultdict(list) for _ in range(m): u, v = list(map(int, stdin.readline().split())) graph[u].append(v) graph[v].append(u) if n <= 6: print(m) exit() else: aux = [] index = [0, 1, 2, 3, 4, 5, 6] total = combinations(index, 2) for i in total: temp = [0] * 7 first, second = i temp[first] = 6 temp[second] = 6 i = 0 val = 1 while i < len(temp): if temp[i] == 0: temp[i] = val val += 1 i += 1 aux.append(temp) ans = 0 for temp in aux: check(temp) print(ans) ```
output
1
50,586
13
101,173
Provide tags and a correct Python 3 solution for this coding contest problem. Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≀ a ≀ b ≀ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph. When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots. How many dominoes at most can Anadi place on the edges of his graph? Input The first line contains two integers n and m (1 ≀ n ≀ 7, 0 ≀ m ≀ (nβ‹…(n-1))/(2)) β€” the number of vertices and the number of edges in the graph. The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≀ a, b ≀ n, a β‰  b) and denote that there is an edge which connects vertices a_i and b_i. The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices. Output Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 4 Input 7 0 Output 0 Input 3 1 1 3 Output 1 Input 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 Output 16 Note Here is an illustration of Anadi's graph from the first sample test: <image> And here is one of the ways to place a domino on each of its edges: <image> Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
instruction
0
50,587
13
101,174
Tags: brute force, graphs Correct Solution: ``` from itertools import product n, m = map(int, input().split()) e = [] for i in range(m): a, b = map(int, input().split()) e.append((a, b)) ans = 0 for idx in product([0], *[list(range(1, 7)) for i in range(n)]): used = [[0] * 7 for i in range(7)] cnt = 0 for u, v in e: u, v = idx[u], idx[v] u, v = min(u, v), max(u, v) if not used[u][v]: used[u][v] = 1 cnt += 1 ans = max(ans, cnt) print(ans) ```
output
1
50,587
13
101,175
Provide tags and a correct Python 3 solution for this coding contest problem. Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≀ a ≀ b ≀ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph. When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots. How many dominoes at most can Anadi place on the edges of his graph? Input The first line contains two integers n and m (1 ≀ n ≀ 7, 0 ≀ m ≀ (nβ‹…(n-1))/(2)) β€” the number of vertices and the number of edges in the graph. The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≀ a, b ≀ n, a β‰  b) and denote that there is an edge which connects vertices a_i and b_i. The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices. Output Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 4 Input 7 0 Output 0 Input 3 1 1 3 Output 1 Input 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 Output 16 Note Here is an illustration of Anadi's graph from the first sample test: <image> And here is one of the ways to place a domino on each of its edges: <image> Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
instruction
0
50,588
13
101,176
Tags: brute force, graphs Correct Solution: ``` n,m=map(int,input().split()) d=[[] for i in range(n+1)] for x in range(m): a,b=map(int,input().split()) d[a].append(b) d[b].append(a) if n<7: print(m) else: ans=-1 for i in range(1,n): for j in range(i+1,n+1): sub=0 for k in range(1,n+1): if k in d[i] and k in d[j]: sub+=1 ans=max(ans,m-sub) print(ans) ```
output
1
50,588
13
101,177
Provide tags and a correct Python 3 solution for this coding contest problem. Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≀ a ≀ b ≀ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph. When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots. How many dominoes at most can Anadi place on the edges of his graph? Input The first line contains two integers n and m (1 ≀ n ≀ 7, 0 ≀ m ≀ (nβ‹…(n-1))/(2)) β€” the number of vertices and the number of edges in the graph. The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≀ a, b ≀ n, a β‰  b) and denote that there is an edge which connects vertices a_i and b_i. The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices. Output Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 4 Input 7 0 Output 0 Input 3 1 1 3 Output 1 Input 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 Output 16 Note Here is an illustration of Anadi's graph from the first sample test: <image> And here is one of the ways to place a domino on each of its edges: <image> Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
instruction
0
50,589
13
101,178
Tags: brute force, graphs Correct Solution: ``` n, m = map(int, input().split()) a = [[*map(int, input().split())] for i in range(m)] from itertools import combinations s = [] ans = 0 def do(): global ans if len(s) == n: t = set() for j in a: y, z = s[j[0] - 1], s[j[1] - 1] if y > z: y, z = z, y t.add((y, z)) ans = max(ans, len(t)) return for i in range(6): s.append(i) do() del s[-1] do() print(ans) ```
output
1
50,589
13
101,179
Provide tags and a correct Python 3 solution for this coding contest problem. Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≀ a ≀ b ≀ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph. When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots. How many dominoes at most can Anadi place on the edges of his graph? Input The first line contains two integers n and m (1 ≀ n ≀ 7, 0 ≀ m ≀ (nβ‹…(n-1))/(2)) β€” the number of vertices and the number of edges in the graph. The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≀ a, b ≀ n, a β‰  b) and denote that there is an edge which connects vertices a_i and b_i. The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices. Output Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 4 Input 7 0 Output 0 Input 3 1 1 3 Output 1 Input 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 Output 16 Note Here is an illustration of Anadi's graph from the first sample test: <image> And here is one of the ways to place a domino on each of its edges: <image> Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
instruction
0
50,590
13
101,180
Tags: brute force, graphs Correct Solution: ``` n, m = [int(i) for i in input().split()] data = [] for i in range(m): data.append([int(j) - 1 for j in input().split()]) ans = 0 for i in range(6 ** n): k = i num = [0] * n for j in range(n): dig = k % 6 k //= 6 num[j] = dig st = set() for e in data: t = [num[e[0]],num[e[1]]] if t[0] > t[1]: t.reverse() st.add(tuple(t)) ans = max(len(st), ans) print(ans) ```
output
1
50,590
13
101,181
Provide tags and a correct Python 3 solution for this coding contest problem. Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≀ a ≀ b ≀ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph. When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots. How many dominoes at most can Anadi place on the edges of his graph? Input The first line contains two integers n and m (1 ≀ n ≀ 7, 0 ≀ m ≀ (nβ‹…(n-1))/(2)) β€” the number of vertices and the number of edges in the graph. The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≀ a, b ≀ n, a β‰  b) and denote that there is an edge which connects vertices a_i and b_i. The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices. Output Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 4 Input 7 0 Output 0 Input 3 1 1 3 Output 1 Input 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 Output 16 Note Here is an illustration of Anadi's graph from the first sample test: <image> And here is one of the ways to place a domino on each of its edges: <image> Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
instruction
0
50,591
13
101,182
Tags: brute force, graphs Correct Solution: ``` import sys input = sys.stdin.readline N, M = map(int, input().split()) Edges = [list(map(lambda x:int(x)-1, input().split())) for _ in range(M)] def dfs(maxd, L, ans): if len(L) == N: dominos = [set() for _ in range(7)] score = 0 for a, b in Edges: ca, cb = L[a], L[b] if ca in dominos[cb]: continue dominos[ca].add(cb) dominos[cb].add(ca) score += 1 #print(L, score) return max(score, ans) for l in range(maxd+2): if l == 6: continue ans = dfs(max(maxd,l), L+[l], ans) return ans print(dfs(-1, [], -2)) ```
output
1
50,591
13
101,183
Provide tags and a correct Python 3 solution for this coding contest problem. Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≀ a ≀ b ≀ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph. When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots. How many dominoes at most can Anadi place on the edges of his graph? Input The first line contains two integers n and m (1 ≀ n ≀ 7, 0 ≀ m ≀ (nβ‹…(n-1))/(2)) β€” the number of vertices and the number of edges in the graph. The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≀ a, b ≀ n, a β‰  b) and denote that there is an edge which connects vertices a_i and b_i. The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices. Output Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 4 Input 7 0 Output 0 Input 3 1 1 3 Output 1 Input 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 Output 16 Note Here is an illustration of Anadi's graph from the first sample test: <image> And here is one of the ways to place a domino on each of its edges: <image> Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
instruction
0
50,592
13
101,184
Tags: brute force, graphs Correct Solution: ``` n,m=map(int,input().split()) L=[] for i in range(n+1): h=[] L.append(h) arr=[] for i in range(m): u,v=map(int,input().split()) L[u].append(v) L[v].append(u) arr.append((u,v)) if(n<7): print(m) else: ans=0 for i in range(1,8): ed=[] for j in range(0,len(L[i])): if(L[i][j]>i): ed.append(L[i][j]-1) else: ed.append(L[i][j]) pre=dict() for j in range(0,len(arr)): x=arr[j][0] y=arr[j][1] if(x!=i and y!=i): if(x>i): x-=1 if(y>i): y-=1 pre[(x,y)]=1 pre[(y,x)]=1 ct=0 for j in range(1,7): c=0 for k in range(0,len(ed)): if(pre.get((j,ed[k]))==None): c+=1 ct=max(c,ct) fnl=m-len(L[i])+ct ans=max(ans,fnl) print(ans) ```
output
1
50,592
13
101,185
Provide tags and a correct Python 3 solution for this coding contest problem. Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≀ a ≀ b ≀ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph. When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots. How many dominoes at most can Anadi place on the edges of his graph? Input The first line contains two integers n and m (1 ≀ n ≀ 7, 0 ≀ m ≀ (nβ‹…(n-1))/(2)) β€” the number of vertices and the number of edges in the graph. The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≀ a, b ≀ n, a β‰  b) and denote that there is an edge which connects vertices a_i and b_i. The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices. Output Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 4 Input 7 0 Output 0 Input 3 1 1 3 Output 1 Input 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 Output 16 Note Here is an illustration of Anadi's graph from the first sample test: <image> And here is one of the ways to place a domino on each of its edges: <image> Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
instruction
0
50,593
13
101,186
Tags: brute force, graphs Correct Solution: ``` import logging from collections import defaultdict def calc_assigned_edge_nums(n, m, edges, new_comer): d_v2n = {} v = 1 for i in range(1, n + 1): if i == new_comer: d_v2n[i] = 7 else: d_v2n[i] = v v += 1 g = defaultdict(set) for a, b in edges: na, nb = d_v2n[a], d_v2n[b] g[na].add(nb) g[nb].add(na) for i in range(1, n): if len(g[i]) == 0: return m dominoes = {(a, b) for b in range(1, 7) for a in range(1, b + 1)} num_of_already_assigned_dominoes = 0 for vertex_from, v in g.items(): for vertex_to in v: domino = tuple(sorted([vertex_from, vertex_to])) # domino_to_remove = domino if domino in dominoes: num_of_already_assigned_dominoes += 1 dominoes.discard(domino) logging.debug('remain dominoes {}'.format(dominoes)) max_assignable_edges_to_7 = 0 for candidate in range(1, 7): # assign 1-6 dot for vertex 7 num_of_assignable_edges = 0 for vertex_from in g[7]: domino = tuple(sorted([vertex_from, candidate])) if domino in dominoes: num_of_assignable_edges += 1 max_assignable_edges_to_7 = max(max_assignable_edges_to_7, num_of_assignable_edges) return num_of_already_assigned_dominoes + max_assignable_edges_to_7 def solve(n, m, edges=list()): if n <= 6: return m maximum_r = 0 for i in range(1, n): # choose which should be new comer r = calc_assigned_edge_nums(n, m, edges, i) logging.debug('#{}= {}'.format(i, r)) maximum_r = max(maximum_r, r) return maximum_r _DEBUG = False if _DEBUG: logging.basicConfig(level=logging.DEBUG) assert solve(7, 21, [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (3, 4), (3, 5), (3, 6), (3, 7), (4, 5), (4, 6), (4, 7), (5, 6), (5, 7), (6, 7)]) == 16 assert solve(4, 4, [(1, 2), (2, 3), (3, 4), (4, 1)]) == 4 assert solve(7, 0) == 0 assert solve(3, 1, [(1, 3)]) == 1 else: logging.basicConfig(level=logging.WARN) _n, _m = map(int, input().split()) _edges = [] for _ in range(_m): a, b = map(int, input().split()) _edges.append([a, b]) print(solve(_n, _m, _edges)) ```
output
1
50,593
13
101,187
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≀ a ≀ b ≀ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph. When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots. How many dominoes at most can Anadi place on the edges of his graph? Input The first line contains two integers n and m (1 ≀ n ≀ 7, 0 ≀ m ≀ (nβ‹…(n-1))/(2)) β€” the number of vertices and the number of edges in the graph. The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≀ a, b ≀ n, a β‰  b) and denote that there is an edge which connects vertices a_i and b_i. The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices. Output Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 4 Input 7 0 Output 0 Input 3 1 1 3 Output 1 Input 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 Output 16 Note Here is an illustration of Anadi's graph from the first sample test: <image> And here is one of the ways to place a domino on each of its edges: <image> Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots. Submitted Solution: ``` n, m = map(int, input().split()) s = [[0 for i in range(n)] for i2 in range(n)] for i in range(m): a, b = map(int, input().split()) s[a - 1][b - 1] = 1 s[b - 1][a - 1] = 1 if n == 7: mass = [] for i in range(n): for i2 in range(n): k = 0 for i3 in range(n): if s[i][i3] == 1 and s[i2][i3] == 1: k += 1 mass += [k] m -= min(mass) print(m) ```
instruction
0
50,594
13
101,188
Yes
output
1
50,594
13
101,189
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≀ a ≀ b ≀ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph. When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots. How many dominoes at most can Anadi place on the edges of his graph? Input The first line contains two integers n and m (1 ≀ n ≀ 7, 0 ≀ m ≀ (nβ‹…(n-1))/(2)) β€” the number of vertices and the number of edges in the graph. The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≀ a, b ≀ n, a β‰  b) and denote that there is an edge which connects vertices a_i and b_i. The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices. Output Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 4 Input 7 0 Output 0 Input 3 1 1 3 Output 1 Input 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 Output 16 Note Here is an illustration of Anadi's graph from the first sample test: <image> And here is one of the ways to place a domino on each of its edges: <image> Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots. Submitted Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- n,m=map(int,input().split()) vertex=[[] for j in range(7)] for j in range(m): a,b=map(int,input().split()) vertex[a-1].append(b-1) vertex[b-1].append(a-1) #find the n vertices that have the most edges most=m if n==7: #make the first 2 the same #consider their intersection maxsofar=-7 for s in range(7): v0=set(vertex[s]) for j in range(s+1,7): v1=set(vertex[j]) length=len(v0.union(v1))-(len(v0)+len(v1)) if length>maxsofar: maxsofar=length most+=maxsofar if n<=6: print(m) else: print(most) ```
instruction
0
50,595
13
101,190
Yes
output
1
50,595
13
101,191
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≀ a ≀ b ≀ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph. When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots. How many dominoes at most can Anadi place on the edges of his graph? Input The first line contains two integers n and m (1 ≀ n ≀ 7, 0 ≀ m ≀ (nβ‹…(n-1))/(2)) β€” the number of vertices and the number of edges in the graph. The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≀ a, b ≀ n, a β‰  b) and denote that there is an edge which connects vertices a_i and b_i. The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices. Output Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 4 Input 7 0 Output 0 Input 3 1 1 3 Output 1 Input 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 Output 16 Note Here is an illustration of Anadi's graph from the first sample test: <image> And here is one of the ways to place a domino on each of its edges: <image> Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots. Submitted Solution: ``` from collections import defaultdict n, m = map(int, input().split()) graph = defaultdict(set) for _ in range(m): a, b = map(int, input().split()) graph[a].add(b) graph[b].add(a) ans = 100 for i in range(1, 7): for j in range(i + 1, 8): g = graph[i] & graph[j] ans = min(ans, len(g)) print(m - ans) ```
instruction
0
50,596
13
101,192
Yes
output
1
50,596
13
101,193