input
stringlengths
20
127k
target
stringlengths
20
119k
problem_id
stringlengths
6
6
import sys input = sys.stdin.readline from collections import Counter from collections import deque def main(): N = int(eval(input())) C = [] T = [[] for j in range(N + 1)] for i in range(N - 1): a, b = [int(x) for x in input().split()] T[a].append([b, i]) T[b].append([a, i]) C.append(a) C.append(b) c = Counter(C) print((c.most_common(1)[0][1])) q = deque() q.append([1, 0]) visited = set() ans = [0] * N while q: i, color = q.popleft() visited.add(i) now_color = 0 for v, j in T[i]: if not v in visited: now_color += 1 if now_color == color: now_color += 1 q.append([v, now_color]) ans[j] = now_color for i in range(N - 1): print((ans[i])) if __name__ == '__main__': main()
import sys input = sys.stdin.readline from collections import deque def main(): N = int(eval(input())) C = [] T = [[] for j in range(N + 1)] for i in range(N - 1): a, b = [int(x) for x in input().split()] T[a].append([b, i]) T[b].append([a, i]) C.append(a) C.append(b) q = deque() q.append([1, 0]) visited = set() ans = [0] * N while q: i, color = q.popleft() visited.add(i) now_color = 0 for v, j in T[i]: if not v in visited: now_color += 1 if now_color == color: now_color += 1 q.append([v, now_color]) ans[j] = now_color print((max(ans))) for i in range(N - 1): print((ans[i])) if __name__ == '__main__': main()
p02850
def resolve(): N = int(eval(input())) g = {} edges = [] for _ in range(N-1): a, b = list(map(int, input().split())) g.setdefault(a-1, []) g[a-1].append(b-1) g.setdefault(b-1, []) g[b-1].append(a-1) edges.append((a-1, b-1)) nodes = [(None, 0)] colors = [[None for _ in range(N)] for _ in range(N)] maxdeg = 0 while nodes: prevcol, node = nodes.pop() maxdeg = max(maxdeg, len(g[node])) #print(colors) #print(prev, node, prevcol) #print(cols) idx = 0 for col in range(1, len(g[node])+1): if col == prevcol: continue nxt = g[node][idx] if colors[node][nxt] is not None: idx += 1 if idx >= len(g[node]): break nxt = g[node][idx] colors[node][nxt] = col colors[nxt][node] = col nodes.append((col, nxt)) idx += 1 if idx >= len(g[node]): break print(maxdeg) for src, dst in edges: print((colors[src][dst])) if '__main__' == __name__: resolve()
def resolve(): N = int(eval(input())) g = {} edges_to_idx = {} edges = [] for i in range(N-1): a, b = list(map(int, input().split())) g.setdefault(a-1, []) g[a-1].append(b-1) g.setdefault(b-1, []) g[b-1].append(a-1) edges_to_idx.setdefault("{}-{}".format(a-1, b-1), i) edges_to_idx.setdefault("{}-{}".format(b-1, a-1), i) edges.append((a-1, b-1)) nodes = [(None, 0)] colors = [None for _ in range(N-1)] maxdeg = 0 while nodes: prevcol, node = nodes.pop() maxdeg = max(maxdeg, len(g[node])) idx = 0 for col in range(1, len(g[node])+1): if col == prevcol: continue nxt = g[node][idx] coloridx = edges_to_idx["{}-{}".format(node, nxt)] if colors[coloridx] is not None: idx += 1 if idx >= len(g[node]): break nxt = g[node][idx] coloridx = edges_to_idx["{}-{}".format(node, nxt)] colors[coloridx] = col nodes.append((col, nxt)) idx += 1 if idx >= len(g[node]): break print(maxdeg) for col in colors: print(col) if '__main__' == __name__: resolve()
p02850
def resolve(): N = int(eval(input())) g = {} edges_to_idx = {} edges = [] for i in range(N-1): a, b = list(map(int, input().split())) g.setdefault(a-1, []) g[a-1].append(b-1) g.setdefault(b-1, []) g[b-1].append(a-1) edges_to_idx.setdefault("{}-{}".format(a-1, b-1), i) edges_to_idx.setdefault("{}-{}".format(b-1, a-1), i) edges.append((a-1, b-1)) nodes = [(None, 0)] colors = [None for _ in range(N-1)] maxdeg = 0 while nodes: prevcol, node = nodes.pop() maxdeg = max(maxdeg, len(g[node])) idx = 0 for col in range(1, len(g[node])+1): if col == prevcol: continue nxt = g[node][idx] coloridx = edges_to_idx["{}-{}".format(node, nxt)] if colors[coloridx] is not None: idx += 1 if idx >= len(g[node]): break nxt = g[node][idx] coloridx = edges_to_idx["{}-{}".format(node, nxt)] colors[coloridx] = col nodes.append((col, nxt)) idx += 1 if idx >= len(g[node]): break print(maxdeg) for col in colors: print(col) if '__main__' == __name__: resolve()
def resolve(): N = int(eval(input())) g = {} for i in range(N-1): a, b = list(map(int, input().split())) g.setdefault(a-1, []) g[a-1].append((b-1, i)) g.setdefault(b-1, []) g[b-1].append((a-1, i)) nodes = [(None, 0)] colors = [None for _ in range(N-1)] maxdeg = 0 while nodes: prevcol, node = nodes.pop() maxdeg = max(maxdeg, len(g[node])) color = 1 if prevcol != 1 else 2 for nxt, colidx in g[node]: if colors[colidx] is None: colors[colidx] = color nodes.append((color, nxt)) color += 1 if prevcol != color+1 else 2 print(maxdeg) for col in colors: print(col) if '__main__' == __name__: resolve()
p02850
import sys from collections import defaultdict from copy import deepcopy input = sys.stdin.readline N = int(eval(input())) edge = [] color_dict = {} repn = [[] for _ in range(N)] for _ in range(N-1): a, b = list(map(int, input().split())) a -= 1 b -= 1 edge.append((a, b)) color_dict[(a, b)] = None repn[a].append(b) repn[b].append(a) K = 0 for i in range(N): K = max(K, len(repn[i])) color_set = set([i for i in range(1, K + 1)]) print(K) q = [(0, K + 1)] while q: u, color = q.pop() c_set = deepcopy(color_set) c_set.discard(color) for v in repn[u]: if color_dict[(u, v)] == None: c = c_set.pop() color_dict[(u, v)] = c color_dict[(v, u)] = c q.append((v, c)) for pair in edge: print((color_dict[pair]))
import sys from collections import defaultdict from copy import deepcopy input = sys.stdin.readline N = int(eval(input())) edge = [] color_dict = {} repn = [[] for _ in range(N)] for _ in range(N-1): a, b = list(map(int, input().split())) a -= 1 b -= 1 edge.append((a, b)) color_dict[(a, b)] = None repn[a].append(b) repn[b].append(a) K = 1 q = [(0, None)] while q: u, color = q.pop() if color == 1: c = 2 else: c = 1 for v in repn[u]: if color_dict[(u, v)] == None: color_dict[(u, v)] = c color_dict[(v, u)] = c q.append((v, c)) K = max(K, c) c += 1 if c == color: c += 1 print(K) for pair in edge: print((color_dict[pair]))
p02850
#!/usr/bin python3 # -*- coding: utf-8 -*- from collections import deque def main(): N = int(eval(input())) Node = [set() for _ in range(N)] Edge = {} for i in range(N-1): a , b = list(map(int, input().split())) a-=1 b-=1 if b<a: a, b = b, a Edge[(a, b)]=i Node[a].add(b) Node[b].add(a) K = 0 for i, x in enumerate(Node): if len(x)>K: K = len(x) top = i q = deque() seen = [False]*(N-1) used = [set() for _ in range(N)] q.append(top) while len(q)>0: cur = q.popleft() for i in Node[cur]: if cur>i: ed = (i, cur) else: ed = (cur, i) if seen[Edge[ed]]==False: col = 1 while col in used[cur] or col in used[i]: col+=1 seen[Edge[ed]] = col used[cur].add(col) used[i].add(col) q.append(i) print(K) print(('\n'.join(map(str, seen)))) if __name__ == '__main__': main()
#!/usr/bin python3 # -*- coding: utf-8 -*- from collections import deque def main(): N = int(eval(input())) Node = [set() for _ in range(N)] Edge = {} for i in range(N-1): a , b = list(map(int, input().split())) a-=1 b-=1 if b<a: a, b = b, a Edge[(a, b)]=i Node[a].add(b) Node[b].add(a) K = 0 for i, x in enumerate(Node): if len(x)>K: K = len(x) top = i q = deque() seen = [False]*(N-1) used = [set() for _ in range(N)] q.append(top) while len(q)>0: cur = q.popleft() col = 1 for i in Node[cur]: if cur>i: ed = (i, cur) else: ed = (cur, i) if seen[Edge[ed]]==False: while col in used[cur] or col in used[i]: col+=1 seen[Edge[ed]] = col used[cur].add(col) used[i].add(col) q.append(i) print(K) print(('\n'.join(map(str, seen)))) if __name__ == '__main__': main()
p02850
N = int(input().strip()) #n_list = [[] for i in range(N)] d = [0] * N connect = [[-1 for i in range(N)] for j in range(N)] for i in range(N-1): a, b = list(map(int, input().strip().split())) a -= 1 b -= 1 connect[a][b] = i connect[b][a] = i d[a] += 1 d[b] += 1 max_index = -1 max_degree = -1 for i in range(N): if d[i] > max_degree: max_degree = d[i] max_index = i colors = [0] * (N-1) root = max_index def paint(node, parent_edge_id): tmp_color = 1 for i in range(N): edge_id = connect[node][i] if edge_id == -1: continue if edge_id != parent_edge_id: if parent_edge_id != -1 and tmp_color == colors[parent_edge_id]: tmp_color += 1 colors[edge_id] = tmp_color paint(i, edge_id) tmp_color += 1 try: paint(root, -1) except TypeError: print((0)) print(max_degree) # color num a for i in range(N-1): print((colors[i]))
import sys N = int(input().strip()) n_list = [[] for i in range(N)] d = [0] * N for i in range(N-1): a, b = list(map(int, input().strip().split())) a -= 1 b -= 1 n_list[a].append([b,i]) n_list[b].append([a,i]) d[a] += 1 d[b] += 1 #print(n_list) #print(d) d_dict = {} for i in range(N): d_dict[i] = d[i] tmp = sorted(list(d_dict.items()), key = lambda x:x[1], reverse = True) colors = [0] * (N) root = tmp[0][0] def paint(node, parent_edge_id): #print(node, parent_edge_id) tmp_color = 1 for edge in n_list[node]: #print("ege:", edge) if edge[1] != parent_edge_id: if parent_edge_id != -1 and tmp_color == colors[parent_edge_id]: tmp_color += 1 colors[edge[1]] = tmp_color paint(edge[0], edge[1]) tmp_color += 1 sys.setrecursionlimit(10**7) paint(tmp[0][0], -1) print((tmp[0][1])) # color num for i in range(N-1): print((colors[i]))
p02850
import sys n=int(eval(input())) g=[[] for _ in range(n)] for i in range(n-1): a,b=list(map(int,sys.stdin.readline().split())) g[a-1].append([b-1,i]) g[b-1].append([a-1,i]) print((max(len(v) for v in g))) from collections import deque l=[0]*(n-1) q=deque([0]) b=[1]+[0]*(n-1) while q: v=q.pop() c=-1 k=1 for u,e in g[v]: if b[u]: c=l[e] for u,e in g[v]: if b[u]: continue if k==c: k+=1 l[e]=k k+=1 q.appendleft(u) b[u]=1 for c in l: print(c)
import sys sys.setrecursionlimit(10**6) n=int(eval(input())) g=[[] for _ in range(n)] for i in range(n-1): a,b=list(map(int,input().split())) g[a-1]+=[(b-1,i)] g[b-1]+=[(a-1,i)] l=[0]*(n-1) def dfs(v,p=-1,s=-1): t=1 for c,i in g[v]: if c==p: continue if t==s: t+=1 l[i]=t dfs(c,v,t) t+=1 dfs(0) print((max(l))) for i in l: print(i)
p02850
from collections import deque from heapq import heappop import sys input = sys.stdin.readline N = int(eval(input())) T = [] D = [0]*N V = [[] for _ in range(N)] argmax = 0 for i in range(N-1): a, b = list(map(int, input().split())) a -= 1 b -= 1 D[a] += 1 D[b] += 1 if D[argmax] < D[a]: argmax = a if D[argmax] < D[b]: argmax = b T.append((a, b)) V[a].append(b) V[b].append(a) d = max(D) for M in [d, d+1]: flag = False Q = deque([argmax]) check = [0]*N color = [2**M-1 for _ in range(N)] C = dict() while Q: v = Q.popleft() check[v] = 1 for u in V[v]: if check[u]: continue else: Q.append(u) usable_colors = color[v] & color[u] if usable_colors == 0: flag = True break else: cnt = 0 while usable_colors % 2 == 0: usable_colors //= 2 cnt += 1 C[tuple(sorted([u, v]))] = cnt color[v] -= 2**cnt color[u] -= 2**cnt if flag: break if M == d and flag == False: break ans = [0]*(N-1) for i in range(N-1): ans[i] = C[T[i]]+1 print((max(ans))) for i in range(N-1): print((ans[i]))
from collections import deque import sys input = sys.stdin.readline N = int(eval(input())) T = [] D = [0]*N V = [[] for _ in range(N)] argmax = 0 for i in range(N-1): a, b = list(map(int, input().split())) a -= 1 b -= 1 D[a] += 1 D[b] += 1 if D[argmax] < D[a]: argmax = a if D[argmax] < D[b]: argmax = b T.append((a, b)) V[a].append(b) V[b].append(a) K = D[argmax] Q = deque([]) C = dict() for i, v in enumerate(V[argmax]): C[tuple(sorted([argmax, v]))] = i+1 Q.append((v, i+1)) check = [0]*N check[argmax] = 1 while Q: v, color = Q.popleft() check[v] = 1 i = 0 for u in V[v]: if check[u]: continue i += 1 if i == color: i += 1 C[tuple(sorted([u, v]))] = i Q.append((u, i)) print(K) for i in range(N-1): print((C[T[i]]))
p02850
import sys sys.setrecursionlimit(10 ** 7) from collections import defaultdict as dd input = sys.stdin.readline N = int(eval(input())) e = dd(list) for i in range(N - 1): a, b = tuple(map(int, input().split())) e[a].append((b, i)) e[b].append((a, i)) res = [0] * (N - 1) vis = set() def dfs(x): global vis global res viss = set() svis = set() t = 1 for y, i in e[x]: if i in vis: viss.add(res[i]) #print(x, viss) for y, i in e[x]: #print(x, y, t) while t in viss: t += 1 if i in vis: continue #print(x, y, t) svis.add(y) vis.add(i) res[i] = t t += 1 dfs(y) #print(res) dfs(1) print((max(res))) for r in res: print(r)
import sys from collections import defaultdict as dd input = sys.stdin.readline sys.setrecursionlimit(10 ** 6) N = int(eval(input())) e = dd(list) for i in range(N - 1): u, v = list(map(int, input().split())) e[u].append((v, i)) e[v].append((u, i)) res = [0] * (N - 1) def dfs(x): global res c = 1 vis = set() for y, i in e[x]: vis.add(res[i]) #print(x, vis) for y, i in e[x]: if res[i] > 0: continue while c in vis: c += 1 #print(x, c) res[i] = c vis.add(c) dfs(y) dfs(1) print((max(res))) for r in res: print(r)
p02850
# D - Coloring Edges on Tree n = int(eval(input())) A = [] B = [] # 2次元配列で辺(頂点,遷移先の頂点)を管理する D = [[] for _ in range(n)] # 2次元配列で塗る色(頂点,遷移先の頂点)を管理する C = [[0]*n for _ in range(n)] for _ in range(n-1): a, b = list(map(int, input().split())) a -= 1 b -= 1 D[a].append(b) D[b].append(a) A.append(a) B.append(b) print((max([len(d) for d in D]))) def dfs(node, par, col): cid = 1 for chi in D[node]: if chi==par: continue else: if cid==col: cid += 1 C[node][chi] = cid dfs(chi, node, cid) cid += 1 dfs(0,0,0) for a, b in zip(A, B): print((C[a][b]))
# D - Coloring Edges on Tree import sys sys.setrecursionlimit(10**6) n = int(eval(input())) A = [] B = [] # 2次元配列で辺(頂点,遷移先の頂点)を管理する D = [[] for _ in range(n)] for _ in range(n-1): a, b = list(map(int, input().split())) a -= 1 b -= 1 D[a].append(b) D[b].append(a) A.append(a) B.append(b) print((max([len(d) for d in D]))) C = {} def dfs(node, par, col): cid = 1 for chi in D[node]: if chi==par: continue else: if cid==col: cid += 1 C[(node, chi)] = cid C[(chi, node)] = cid dfs(chi, node, cid) cid += 1 dfs(0,0,0) for a, b in zip(A, B): print((C[(a,b)]))
p02850
import sys sys.setrecursionlimit(1000000) n = int(eval(input())) g = [[] for _ in range(n)] for i in range(n-1): a, b = list(map(int, input().split())) a, b = a-1, b-1 g[a].append([b, i]) g[b].append([a, i]) ans = [0]*(n-1) def dfs(v, c=-1, p=-1): k = 1 for u, ei in g[v]: if u == p: continue if k == c: k += 1 ans[ei] = k k += 1 dfs(u, ans[ei], v) dfs(0) print((max(ans))) for i in range(n-1): print((ans[i]))
import sys input = sys.stdin.readline n = int(eval(input())) g = [[] for _ in range(n)] e = [] for i in range(n-1): a, b = list(map(int, input().split())) a, b = a-1, b-1 g[a].append(b) g[b].append(a) e.append((a, b)) # topological順序の計算 s = [] s.append(0) parent = [-1]*n order = [] while s: x = s.pop() order.append(x) for nx in g[x]: if nx == parent[x]: continue parent[nx] = x s.append(nx) color = [0]*n for v in order: ng = color[v] c = 1 for u in g[v]: if u == parent[v]: continue if c == ng: c += 1 color[u] = c c += 1 ans = [] for a, b in e: if parent[a] == b: ans.append(color[a]) else: ans.append(color[b]) print((len(set(ans)))) print(('\n'.join(map(str,ans))))
p02850
import sys from collections import deque sys.setrecursionlimit(10**7) n = int(eval(input())) graph = {i : [] for i in range(n)} ls = [] for i in range(n-1): a, b = [int(i) for i in sys.stdin.readline().split()] a -= 1 b -= 1 ls.append((a,b)) graph[a].append(b) graph[b].append(a) _max = 0 _max_node = None for k, v in list(graph.items()): if len(v) > _max: _max = len(v) _max_node = k colors = [[0 for i in range(n)] for j in range(n)] que = deque() color_dict = {i : set(range(1,1+_max)) for i in range(n)} cur = _max_node already = set() while True: cnt = 1 already.add(cur) for _next in graph[cur]: if colors[cur][_next] == 0: if _next not in already: que.append(_next) already.add(_next) candidate = color_dict[_next].intersection(color_dict[cur]) cnt = list(candidate)[0] colors[cur][_next] = cnt colors[_next][cur] = cnt color_dict[cur].remove(cnt) color_dict[_next].remove(cnt) if len(que) == 0: break cur = que.popleft() print(_max) for a, b in ls: print((colors[a][b]))
import sys from collections import deque sys.setrecursionlimit(10**7) n = int(eval(input())) graph = {i : [] for i in range(n)} ls = [] for i in range(n-1): a, b = [int(i) for i in sys.stdin.readline().split()] a -= 1 b -= 1 ls.append((a,b)) graph[a].append(b) graph[b].append(a) _max = 0 _max_node = None for k, v in list(graph.items()): if len(v) > _max: _max = len(v) _max_node = k parent = [_max_node] * (n) order = [] stack = [_max_node] while stack: x = stack.pop() order.append(x) for y in graph[x]: if y == parent[x]: continue parent[y] = x stack.append(y) colors = [-1 for i in range(n)] for i in order: c = 1 for _next in graph[i]: if _next == parent[i]: continue if c == colors[i]: c += 1 colors[_next] = c c += 1 print(_max) for a, b in ls: if parent[a] == b: print((colors[a])) else: print((colors[b]))
p02850
import sys input = sys.stdin.readline N = int(eval(input())) Graph = [[] for _ in range(N)] edges = [] for _ in range(N - 1): a, b = [int(x) - 1 for x in input().split()] edges.append((a, b)) for a, b in edges: Graph[a].append(b) Graph[b].append(a) k = max(len(edges) for edges in Graph) colors = {color for color in range(1, k + 1)} usedcolor = [None for _ in range(N)] colored = {} for v in range(N): unused_colors = colors - { usedcolor[v] } for edge in Graph[v]: # 未着色 if (v, edge) not in colored and (edge, v) not in colored: color = unused_colors.pop() colored[(v, edge)] = colored[(edge, v)] = color usedcolor[edge] = color print(k) for a, b in edges: print((colored[(a, b)]))
import sys input = sys.stdin.readline N = int(eval(input())) Graph = [[] for _ in range(N)] edges = [] for _ in range(N - 1): a, b = [int(x) - 1 for x in input().split()] edges.append((a, b)) for a, b in edges: Graph[a].append(b) Graph[b].append(a) k = max(len(edges) for edges in Graph) colors = [color for color in range(1, k + 1)] usedcolor = [None for _ in range(N)] colored = {} def colors_except(x): for c in colors: if c == x: continue yield c for v in range(N): unused_colors = colors_except(usedcolor[v]) for edge in Graph[v]: # 未着色 if (v, edge) not in colored and (edge, v) not in colored: color = next(unused_colors) colored[(v, edge)] = colored[(edge, v)] = color usedcolor[edge] = color print(k) for a, b in edges: print((colored[(a, b)]))
p02850
#!/usr/bin/env python3 import sys import math from bisect import bisect_right as br from bisect import bisect_left as bl sys.setrecursionlimit(2147483647) from heapq import heappush, heappop,heappushpop from collections import defaultdict from itertools import accumulate from collections import Counter from collections import deque from operator import itemgetter from itertools import permutations mod = 10**9 + 7 inf = float('inf') def I(): return int(sys.stdin.readline()) def LI(): return list(map(int,sys.stdin.readline().split())) n = I() edges = [[] for _ in range(n)] ab = [[i] + LI() for i in range(n-1)] col = [defaultdict(int) for _ in range(n)] cnt = [0] * n for i, a, b in ab: edges[a-1].append((i, b-1)) edges[b-1].append((i, a-1)) cnt[a-1] += 1 cnt[b-1] += 1 k = max(cnt) print(k) used_edge = [False] * n que = deque([(0, -1)]) edges_color = [None] * (n-1) while que: v, p = que.popleft() for i, u in edges[v]: if used_edge[i]: continue if u == p: continue cnt = 1 while col[u][cnt] or col[v][cnt]: cnt += 1 col[u][cnt] = 1 col[v][cnt] = 1 edges_color[i] = cnt used_edge[i] = False que.append((u, v)) for c in edges_color: print(c)
#!/usr/bin/env python3 import sys import math from bisect import bisect_right as br from bisect import bisect_left as bl sys.setrecursionlimit(2147483647) from heapq import heappush, heappop,heappushpop from collections import defaultdict from itertools import accumulate from collections import Counter from collections import deque from operator import itemgetter from itertools import permutations mod = 10**9 + 7 inf = float('inf') def I(): return int(sys.stdin.readline()) def LI(): return list(map(int,sys.stdin.readline().split())) n = I() edges = [[] for _ in range(n)] ab = [[i] + LI() for i in range(n-1)] cnt = [0] * n for i, a, b in ab: edges[a-1].append((i, b-1)) edges[b-1].append((i, a-1)) cnt[a-1] += 1 cnt[b-1] += 1 k = max(cnt) print(k) que = deque([(0, -1, 0)]) edges_color = [None] * (n-1) while que: v, p, col = que.popleft() cnt = 1 for i, u in edges[v]: if edges_color[i] != None: continue if u == p: continue if cnt != col: edges_color[i] = cnt else: edges_color[i] = cnt + 1 cnt += 1 que.append((u, v, cnt)) cnt += 1 for c in edges_color: print(c)
p02850
import sys import math def func(s): return int(s)-1 N=int(eval(input())) e=[list(map(func,input().split()))+[i] for i in range(N-1)] e.sort() x=[0 for i in range(N)] for i in range(N-1): x[e[i][0]]+=1 x[e[i][1]]+=1 print((max(x))) e2=[[0 for j in range(x[i])]for i in range(N)] ans=[0 for i in range(N-1)] for i in range(N-1): [p,q,r]=e[i] for j in range(x[p]): if e2[p][j]==0: e2[p][j]=1 if j<x[q]: e2[q][j]=1 ans[r]=j break for i in range(N-1): print((ans[i]+1))
import sys import math def func(s): return int(s)-1 N=int(eval(input())) e=[list(map(func,input().split()))+[i] for i in range(N-1)] e.sort() x=[0 for i in range(N)] for i in range(N-1): x[e[i][0]]+=1 x[e[i][1]]+=1 print((max(x))) e2=[[0 for j in range(x[i])]for i in range(N)] ans=[0 for i in range(N-1)] y=[0 for i in range(N)] for i in range(N-1): [p,q,r]=e[i] e2[p][y[p]]=1 if y[p]<x[q]: e2[q][y[p]]=1 ans[r]=y[p] for j in range(y[p],x[p]): if e2[p][j]==0: y[p]=j break for j in range(y[q],x[q]): if e2[q][j]==0: y[q]=j break for i in range(N-1): print((ans[i]+1))
p02850
from collections import deque n = int(eval(input())) edges = {} lst = [set()for i in range(n)] vert = [set() for i in range(n)] ans = [0 for i in range(n-1)] for i in range(n-1): a,b = list(map(int,input().split())) lst[a-1].add(b) lst[b-1].add(a) if a > b: a,b = b,a edges[(a,b)] = i q = deque([1]) while q: x = q.popleft() q.extend(lst[x-1]) while lst[x-1]: i = lst[x-1].pop() lst[i-1].discard(x) a = min(x,i) b = max(x,i) for j in range(1,n): if not (j in vert[x-1] or j in vert[i-1]): vert[x-1].add(j) vert[i-1].add(j) ans[edges[(a,b)]] = j break print((max(ans))) for i in range(len(ans)): print((ans[i]))
n = int(eval(input())) graph = [[] for _ in range(n+1)] for i in range(1,n): a,b = list(map(int,input().split())) graph[a].append((i,b)) graph[b].append((i,a)) colors = [0 for _ in range(n)] parents = [0]*(n+1) stack = [(1,0)] while stack: x,c = stack.pop() color = 1 for i,y in graph[x]: if parents[x] == y: continue else: parents[y] = x if color == c: color += 1 colors[i] = color stack.append((y,color)) color += 1 print((max(colors))) for i in range(1,n): print((colors[i]))
p02850
from collections import deque N = int(eval(input())) node = [[]for i in range(N)] side = [] ans = [0]*(N-1) watch = [0]*N watch[0] = 1 for i in range(N-1): a,b = list(map(int,input().split())) side.append([a-1,b-1]) node[a-1].append(i) node[b-1].append(i) K = max(len(i) for i in node) print(K) queue = deque([0]) while queue: q = queue.popleft() use = [0]*(K+1) for i in node[q]: use[ans[i]] = 1 p = 1 for i in node[q]: if ans[i] == 0: while use[p]: p += 1 ans[i] = p use[p] = 1 s = side[i] next = s[(s.index(q)+1)%2] if watch[next] == 0: queue.append(next) watch[next] = 1 for i in ans: print(i)
from collections import deque N = int(eval(input())) node = [[]for i in range(N)] side = [] count = [0]*N ans = [0]*(N-1) closed = [0]*N for i in range(N-1): a,b = list(map(int,input().split())) side.append([a-1, b-1]) node[a-1].append(i) node[b-1].append(i) count[a-1] += 1 count[b-1] += 1 K = max(count) print(K) queue = deque([[0,K+1]]) while queue: q,m = queue.popleft() p = 1 for i in node[q]: if p == m: p += 1 if ans[i] == 0: ans[i] = p s = side[i] next = s[(s.index(q)+1)%2] if closed[next] == 0: queue.append([next,p]) closed[next] = 1 p += 1 for i in ans: print(i)
p02850
from collections import deque N = int(eval(input())) AB = [list(map(int, input().split())) for _ in range(N-1)] con = [set() for _ in range(N+1)] res = {} for ab in AB: con[ab[0]].add(ab[1]) con[ab[1]].add(ab[0]) res[tuple(ab)] = 0 max_len = 0 for i, c in enumerate(con): if max_len <= len(c): max_len = len(c) max_ind = i colors = [set() for i in range(N+1)] all_colors = set([i for i in range(1, max_len+1)]) q = deque() q.append(max_ind) node_state = [0]*(N+1) while q != deque(): v = q.pop() node_state[v] = 1 for next_v in con[v]: if node_state[next_v] == 0: q.appendleft(next_v) if v < next_v: va = v vb = next_v else: va = next_v vb = v if res[(va, vb)] == 0: color = list(all_colors.difference(colors[va].union(colors[vb])))[0] res[(va, vb)] = color colors[va].add(color) colors[vb].add(color) print(max_len) for i in range(N-1): print((res[tuple(AB[i])]))
N = int(eval(input())) AB = [list(map(int, input().split())) for _ in range(N-1)] sortedAB = sorted(AB) con = {i: [] for i in range(1, N+1)} color = [0] * (N + 1) for a, b in sortedAB: con[a].append(b) for i in range(1, N + 1): now_c = 1 for c in con[i]: if color[i] == now_c: now_c += 1 color[c] = now_c now_c += 1 print((max(color))) for i in range(N-1): print((color[AB[i][1]])) a = 0
p02850
import sys sys.setrecursionlimit(1000000000) input = sys.stdin.readline n=int(eval(input())) es=[[] for i in range(n)] l=[list(map(int,input().split())) for i in range(n-1)] for i in range(n-1): l[i][0]-=1 l[i][1]-=1 l[i][0],l[i][1]=min(l[i][0],l[i][1]),max(l[i][0],l[i][1]) es[l[i][0]].append(l[i][1]) es[l[i][1]].append(l[i][0]) dic={} use=[1]*n def dfs(v,k): cnt=0 use[v]=0 for i in es[v]: if use[i]: if cnt==k: cnt+=1 dic[(min(v,i),max(v,i))]=cnt dfs(i,cnt) cnt+=1 dfs(0,-1) ans=[0]*(n-1) k=0 for i in range(n-1): ans[i]=dic[l[i][0],l[i][1]]+1 k=max(k,ans[i]) print(k) for i in ans: print(i)
import sys sys.setrecursionlimit(1000000000) input = sys.stdin.readline n=int(eval(input())) es=[[] for i in range(n)] l=[list(map(int,input().split())) for i in range(n-1)] for i in range(n-1): l[i][0]-=1 l[i][1]-=1 es[l[i][0]].append(l[i][1]) es[l[i][1]].append(l[i][0]) dic={} use=[1]*n def dfs(v,k): cnt=0 use[v]=0 for i in es[v]: if use[i]: if cnt==k: cnt+=1 dic[(min(v,i),max(v,i))]=cnt dfs(i,cnt) cnt+=1 dfs(0,-1) ans=[0]*(n-1) k=0 for i in range(n-1): ans[i]=dic[l[i][0],l[i][1]]+1 k=max(k,ans[i]) print(k) for i in ans: print(i)
p02850
from collections import deque import copy n = int(eval(input())) Adj_dict = {x:[] for x in range(1,n+1)} AB = [] for _ in range(n-1): a, b = list(map(int, input().split())) Adj_dict[a].append(b) Adj_dict[b].append(a) AB.append([a,b]) max_edges = 0 node_max_edges = 0 for key, value in list(Adj_dict.items()): edges = len(value) if edges >= max_edges: max_edges = edges node = key dq = deque() dq.append(node) Visited = [False for _ in range(n+1)] Visited[node] = True Visited_to = [[] for _ in range(n+1)] Colors = [x for x in range(1, max_edges+1)] Colors_list = [[x for x in range(1, max_edges+1)] for x in range(n+1)] Edge_colors = [[-1 for _ in range(n+1)] for _ in range(n+1)] # print(Colors_list) while dq: # Colors_copy = copy.deepcopy(Colors) node = dq.popleft() Next_nodes = Adj_dict[node] # for v in Visited_from: # Colors_copy.remove(Edge_colors[node][v]) for next_node in Next_nodes: if Visited[next_node] == True: continue dq.append(next_node) Visited_to[next_node].append(node) Visited[next_node] = True use_color = Colors_list[node][0] Colors_list[node].remove(use_color) Colors_list[next_node].remove(use_color) Edge_colors[node][next_node] = use_color Edge_colors[next_node][node] = use_color # del Colors_copy[0] print(max_edges) for ab in AB: print((Edge_colors[ab[0]][ab[1]]))
from collections import deque n = int(eval(input())) Adj_dict = {x:[] for x in range(1,n+1)} AB_dict = {} AB = [] for _ in range(n-1): a, b = list(map(int, input().split())) Adj_dict[a].append(b) Adj_dict[b].append(a) AB.append([a,b]) AB_dict.update({str(a)+'_'+str(b):0}) max_edges = 0 node_max_edges = 0 for key, value in list(Adj_dict.items()): edges = len(value) if edges >= max_edges: max_edges = edges node = key dq = deque() dq.append(1) Visited = [False for _ in range(n+1)] Visited[1] = True Colors = [0 for _ in range(n+1)] while dq: c = 1 node = dq.popleft() Next_nodes = Adj_dict[node] for next_node in Next_nodes: if Visited[next_node] == True: continue dq.append(next_node) Visited[next_node] = True if c == Colors[node]: c += 1 Colors[next_node] = c c += 1 if node < next_node: AB_dict[str(node)+'_'+str(next_node)] = Colors[next_node] else: AB_dict[str(next_node)+'_'+str(node)] = Colors[next_node] print(max_edges) for ab in AB: a = ab[0] b = ab[1] print((AB_dict[str(a)+'_'+str(b)])) # print(AB_dict)
p02850
import queue n = int(eval(input())) #ab = [[]*(n)] ab = [[] for _ in range(n+1)] #print(ab) li = [] for i in range(n-1): a,b = list(map(int,input().split())) ab[a].append(b) ab[b].append(a) li.append([a,b]) ab_color = [[0 for _ in range(n+1)] for _ in range(n+1)] #print(li) q = queue.Queue() check = [0] * (n+1) #check[1] == 1 check_color = [0] * (n+1) q.put(1) color_num = 1 #mae_color = 0 while not q.empty(): tmp_color = 0 tmp = q.get() #print(tmp) #tmp_color = mae_color mae_color = check_color[tmp] for i in range(len(ab[tmp])): if check[ab[tmp][i]] == 1: #print(i,tmp) continue else: #print(mae_color,tmp_color,tmp,i) tmp_color += 1 q.put(ab[tmp][i]) if tmp_color == mae_color: tmp_color += 1 check_color[ab[tmp][i]] = tmp_color ab_color[ab[tmp][i]][tmp] = tmp_color ab_color[tmp][ab[tmp][i]] = tmp_color check[tmp] = 1 if color_num < tmp_color: color_num = tmp_color #color_num = max(color_num,tmp_color) #print(check,i) print(color_num) for i in range(len(li)): print((ab_color[li[i][0]][li[i][1]]))
import queue n = int(eval(input())) #ab = [[]*(n)] ab = [[] for _ in range(n+1)] #print(ab) li = [] for i in range(n-1): a,b = list(map(int,input().split())) ab[a].append([b,i]) ab[b].append([a,i]) #li.append([a,b]) #ab_color = [[None for _ in range(n+1)] for _ in range(n+1)] ans = [0] * (n-1) q = queue.Queue() check = [0] * (n+1) #check[1] == 1 check_color = [0] * (n+1) q.put(1) color_num = 1 #mae_color = 0 while not q.empty(): tmp_color = 0 tmp = q.get() #print(tmp) #tmp_color = mae_color mae_color = check_color[tmp] for i in range(len(ab[tmp])): if check[ab[tmp][i][0]] == 1: #print(i,tmp) continue else: #print(mae_color,tmp_color,tmp,i) tmp_color += 1 q.put(ab[tmp][i][0]) if tmp_color == mae_color: tmp_color += 1 check_color[ab[tmp][i][0]] = tmp_color ans[ab[tmp][i][1]] = tmp_color #ab_color[ab[tmp][i]][tmp] = tmp_color #ab_color[tmp][ab[tmp][i]] = tmp_color check[tmp] = 1 if color_num < tmp_color: color_num = tmp_color #color_num = max(color_num,tmp_color) #print(check,i) print(color_num) for i in range(len(ans)): print((ans[i]))
p02850
if __name__ == "__main__": import sys from collections import deque input = sys.stdin.readline N = int(eval(input())) edges = [[] for _ in range(N)] for i in range(N-1): a,b = list(map(int,input().split())) a -= 1 b -= 1 edges[a].append((b,i)) edges[b].append((a,i)) color = [None]*(N-1) SIZE = 1 q = deque([(0,None)]) while q: v, prev_color = q.popleft() colors = list(range(1,SIZE+1)) if prev_color: colors.remove(prev_color) for w, i in edges[v]: if not color[i]: if colors: color[i] = colors.pop(0) else: SIZE += 1 color[i] = SIZE q.append((w,color[i])) print(SIZE) for n in range(N-1): print((color[n]))
if __name__ == "__main__": import sys from collections import deque input = sys.stdin.readline N = int(eval(input())) edges = [[] for _ in range(N)] for i in range(N-1): a,b = list(map(int,input().split())) a -= 1 b -= 1 edges[a].append((b,i)) edges[b].append((a,i)) color = [None]*(N-1) SIZE = 1 q = deque([(0,None)]) while q: v, prev_color = q.popleft() c = 1 for w, i in edges[v]: if not color[i]: if c == prev_color: c += 1 color[i] = c c += 1 q.append((w,color[i])) SIZE = max(SIZE, c-1) print(SIZE) for n in range(N-1): print((color[n]))
p02850
n=int(eval(input())) g=[[] for _ in range(n)] for i in range(n-1): a,b=list(map(int,input().split())) g[a-1].append((b-1,i)) vc=[[] for _ in range(n)] ec=[-1]*(n-1) for p,ci in enumerate(g): for c, i in ci: color = 1 while True: if color not in vc[p]: vc[p].append(color) vc[c].append(color) ec[i] = color break else: color += 1 print((max(ec))) for i in range(n-1): print((ec[i]))
n=int(eval(input())) g=[[] for _ in range(n)] for i in range(n-1): a,b=list(map(int,input().split())) g[a-1].append((b-1,i)) vc=[0] * n ec=[-1]*(n-1) for p,ci in enumerate(g): color = 1 for c, i in ci: if vc[p] == color: color += 1 vc[c] = color ec[i] = color color += 1 print((max(ec))) for i in range(n-1): print((ec[i]))
p02850
import sys from heapq import heappop as p sys.setrecursionlimit(9**9) n=int(eval(input())) T=[[] for _ in range(n)] for i in range(n-1): a,b=list(map(int,input().split())) T[a-1].append([b-1,i]) C=[0]*(n-1) def f(Q): R=[] for q in Q: H=list(range(1,n)) for t in T[q[0]]: x=p(H) if x==q[1]: x=p(H) C[t[1]]=x if len(T[t[0]])!=0: R.append([t[0],x]) if len(R)!=0: return f(R) f([[0,0]]) print((max(C))) for c in C: print(c)
import sys sys.setrecursionlimit(9**9) n=int(eval(input())) T=[[] for _ in range(n)] for i in range(n-1): a,b=list(map(int,input().split())) T[a-1].append([b-1,i]) C=[0]*(n-1) def f(i,r): c=1 for (x,y) in T[i]: c+=(c==r) C[y]=c f(x,c) c+=1 f(0,0) print((max(C))) for c in C: print(c)
p02850
from collections import deque def bfs(idx,k): q = deque() visited[idx] = True q.append(idx) color = 0 while q: r = q.pop() ver = set(graph[r].keys()) col = [i for i in range(k) if i not in set(graph[r].values())] i = 0 for n in ver: if not visited[n]: graph[r][n] = col[i] graph[n][r] = col[i] i = (i+1)%len(col) visited[n] = True q.append(n) N = int(eval(input())) graph = {} visited = [False]*(N+1) for i in range(N+1): graph[i] = {} ab = [] for i in range(N-1): a,b = list(map(int,input().split())) ab.append((a,b)) graph[a][b] = -1 graph[b][a] = -1 k = max([len(graph[i]) for i in range(1,N+1)]) bfs(1,k) print(k) for a,b in ab: print((graph[a][b]+1))
from collections import deque def bfs(idx,k,colored): q = deque() visited[idx] = True q.append(idx) while q: r = q.pop() color = 0 for n in list(graph[r].keys()): if not visited[n]: if color == colored[r]: color+=1 colored[n] = color graph[r][n] = color graph[n][r] = color color += 1 visited[n] = True q.append(n) N = int(eval(input())) graph = {} colored = [-1]*(N+1) visited = [False]*(N+1) for i in range(N+1): graph[i] = {} ab = [] for i in range(N-1): a,b = list(map(int,input().split())) ab.append((a,b)) graph[a][b] = -1 graph[b][a] = -1 k = max([len(graph[i]) for i in range(1,N+1)]) bfs(1,k,colored) print(k) for a,b in ab: print((graph[a][b]+1))
p02850
from collections import deque n = int(eval(input())) node_list = [] nodes = [[] for _ in range(n)] edges = dict() for _ in range(n - 1): a, b = list(map(int, input().split())) node_list.append((a - 1, b - 1)) nodes[a - 1].append(b - 1) nodes[b - 1].append(a - 1) edges[(a - 1, b - 1)] = 0 used_colors = [[] for _ in range(n)] used = [False] * n que = deque() que.append(0) while len(que) > 0: ni = que.pop() for node in nodes[ni]: [a, b] = sorted([ni, node]) if edges[(a, b)] == 0: for color in range(1, n): if not color in used_colors[a] and not used_colors[b]: break edges[(a, b)] = color used_colors[a].append(color) used_colors[b].append(color) if not used[node]: que.append(node) used[ni] = True print((max(edges.values()))) for node in node_list: print((edges[node]))
from collections import deque n = int(eval(input())) nodes = [[] for _ in range(n)] node_list = [] for _ in range(n - 1): a, b = list(map(int, input().split())) nodes[a - 1].append(b - 1) node_list.append(b - 1) que = deque([0]) ans = [0] * n while len(que) > 0: ni = que.pop() color = 1 for node in nodes[ni]: if color == ans[ni]: color += 1 ans[node] = color color += 1 que.append(node) print((max(ans))) for node in node_list: print((ans[node]))
p02850
N = int(eval(input())) A,B = [0]*(N-1),[0]*(N-1) for i in range(N-1): array = list(map(int,input().split())) A[i] = array[0] B[i] = array[1] from collections import defaultdict as ddict children = ddict(list) for a,b in zip(A,B): children[a].append(b) ans = ddict(int) for child in sorted(children.keys()): used = [False]*100000 used[ans[child]-1] = True for j in sorted(children[child]): temp = used.index(False)+1 ans[j] = temp used[temp-1] = True ans2 = [ans[b] for b in B] print((max(ans2))) for a in ans2: print(a)
N = int(eval(input())) AB = [[]]*(N-1) for i in range(N-1): AB[i] = list(map(int,input().split())) from collections import defaultdict as ddict from collections import deque tree = ddict(list) B = [0]*(N-1) for i,ab in enumerate(AB): tree[ab[0]].append(ab[1]) B[i] = ab[1] # 各エッジの色を格納する変数の初期化 # C[0]は使わない C = [0]*N # 幅優先探索用のcue Q = deque([1]) while Q: q = Q.popleft() c = 0 for w in tree[q]: # 色をインクリメントした際に親の色とかぶったら更に1を加算する # 他は単純なインクリメント c += 1 + int(C[q-1] == c+1) # エッジの色を格納 C[w-1] = c # 子供をcueに追加 Q.append(w) print((max(C))) for b in B: print((C[b-1]))
p02850
import sys sys.setrecursionlimit(10**9) N = int(input()) G = [[] for i in range(N)] for i in range(N-1): a, b = map(int, input().split()) G[a-1].append([b-1,i]) ans = [None]*(N-1) # 引数:今回の基準頂点、前回の基準頂点と今回の頂点を結ぶ辺の色番号 def func(ver, color): # 色番号。まずは最低の番号から始める。もし今回と前回の基準頂点の色番号1の場合は後で色番号変更 cnt = 1 # for (基準頂点と繋がっている頂点, 辺の番号) in 基準頂点 for (to, i) in G[ver]: # 既使用(前回の基準頂点と今回の頂点を結ぶ辺の色)と今回使う色番号が同じなら+1で色番号変更 if cnt==color: cnt += 1 # i番目の辺における色番号 ans[i] = cnt # 今回の頂点と、今回の頂点と基準頂点の辺の色番号を入力し、今回の頂点を次の基準頂点にする func(to, cnt) # 今回の基準頂点と繋がる次の頂点の処理をするために色番号変更 cnt += 1 func(0, 0) print(max(ans)) print(*ans, sep="\n")
import sys sys.setrecursionlimit(10**9) N= int(eval(input())) G = [[] for i in range(N)] for i in range(N-1): a, b = list(map(int, input().split())) G[a-1].append([b-1, i]) ans = [None]*(N-1) def func(prt, col): cnt = 1 for cld, org in G[prt]: if cnt==col: cnt += 1 ans[org] = cnt func(cld, cnt) cnt += 1 func(0, 0) print((max(ans))) for i in range(N-1): print((ans[i]))
p02850
import copy n=int(eval(input())) org=[i for i in range(1,10**5)] org_set=set(org) edges=[] colors=[] for i in range(n-1): a,b=list(map(int,input().split(" "))) edges.append([a,b]) colors.append([]) colors.append([]) colors.append([]) ans=[] for i in edges: color_sum=set(colors[i[0]]+colors[i[1]]) tmp_org=org_set.copy() for j in color_sum: tmp_org.remove(j) org_ls=list(tmp_org) colors[i[0]].append(org_ls[0]) colors[i[1]].append(org_ls[0]) ans.append(org_ls[0]) print((max(ans))) for i in ans: print(i)
import copy n=int(eval(input())) org_set=set([i for i in range(1,10**5)]) edges=[] relations={} nodes=[] for i in range(n-1): a,b=list(map(int,input().split(" "))) edges.append([a,b]) relations.setdefault(a,[]).append(b) nodes.append([]) nodes.append([]) nodes.append([]) max_color=0 for start in range(1,n+1): targets=relations.get(start,[]) color=1 for target in targets: if color in nodes[start]: color+=1 else: pass nodes[target].append(color) if color>=max_color: max_color=color color+=1 print(max_color) for edge in edges: print((nodes[edge[1]][0]))
p02850
import copy n=int(eval(input())) org_set=set([i for i in range(1,10**5)]) edges=[] relations={} nodes=[] for i in range(n-1): a,b=list(map(int,input().split(" "))) edges.append([a,b]) relations.setdefault(a,[]).append(b) nodes.append([]) nodes.append([]) nodes.append([]) max_color=0 for start in range(1,n+1): targets=relations.get(start,[]) color=1 for target in targets: if color in nodes[start]: color+=1 else: pass nodes[target].append(color) if color>=max_color: max_color=color color+=1 print(max_color) for edge in edges: print((nodes[edge[1]][0]))
n=int(eval(input())) edges=[] relations={} nodes=[0,0] for i in range(n-1): a,b=list(map(int,input().split(" "))) edges.append([a,b]) relations.setdefault(a,[]).append(b) nodes.append(0) max_color=0 for start in range(1,n+1): targets=relations.get(start,[]) color=1 for target in targets: if color == nodes[start]: color+=1 else: pass nodes[target]=color if color>=max_color: max_color=color color+=1 print(max_color) for edge in edges: print((nodes[edge[1]]))
p02850
import sys sys.setrecursionlimit(200000) N = int(eval(input())) ans = [0] * (N - 1) AB = [] for i in range(N-1): a,b = list(map(int,input().split())) AB.append([a-1,b-1]) G = [list() for _ in range(N)] for i in range(N-1): G[AB[i][1]].append([AB[i][0],i]) G[AB[i][0]].append([AB[i][1],i]) def dfs(v,c = -1,p = -1): k = 1 for i in range(len(G[v])): u = G[v][i][0];ei = G[v][i][1] if u == p:continue if k == c: k += 1 ans[ei] = k k += 1 dfs(u,ans[ei],v) dfs(0) mx = 0 for i in range(N): mx = max(mx,len(G[i])) print(mx) for i in range(N-1): print((ans[i]))
import sys sys.setrecursionlimit(200000) N = int(eval(input())) ans = [0] * (N - 1) G = [list() for _ in range(N)] for i in range(N-1): a,b = list(map(int,input().split())) a -= 1 b -= 1 G[a].append([b,i]) G[b].append([a,i]) def dfs(v,c = -1,p = -1): k = 1 for i in range(len(G[v])): u = G[v][i][0];ei = G[v][i][1] if u == p:continue if k == c: k += 1 ans[ei] = k k += 1 dfs(u,ans[ei],v) dfs(0) mx = 0 for i in range(N): mx = max(mx,len(G[i])) print(mx) for i in range(N-1): print((ans[i]))
p02850
# -*- coding: utf-8 -*- from collections import deque def main(): input_buffer = """ """ #8 #1 2 #2 3 #2 4 #2 5 #4 7 #5 6 #6 8 INPUT = list(reversed(input_buffer.strip().splitlines())) if INPUT: n = int(INPUT.pop()) edges = [0] * (n-1) for i in range(n-1): edges[i] = tuple(map(int, INPUT.pop().split())) else: n = int(eval(input())) edges = [0] * (n-1) for i in range(n-1): edges[i] = tuple(map(int, input().split())) adjacency_list = [[] for i in range(n+1)] for edge in edges: adjacency_list[edge[0]].append(edge[1]) adjacency_list[edge[1]].append(edge[0]) max_order = max(len(i) for i in adjacency_list) root = 0 for i in range(0, n+1): if len(adjacency_list[i]) == max_order: root = i node_history = set() edge_dict = dict() node_deque = deque() node_deque.append(root) while len(node_deque): current_node = node_deque.popleft() undef_edges = [] kinds = {i for i in range(1, max_order + 1)} for a in adjacency_list[current_node]: if a not in node_history: node_history.add(a) node_deque.append(a) if current_node < a: temp_edge = (current_node, a) else: temp_edge = (a, current_node) if temp_edge in list(edge_dict.keys()): kinds.remove(edge_dict[temp_edge]) else: undef_edges.append(temp_edge) for undef_edge in undef_edges: kind = min(kinds) edge_dict[undef_edge] = kind kinds.remove(kind) print(max_order) for e in edges: print((edge_dict[e])) if __name__ == "__main__": main()
from collections import deque def main(): N, *AB = list(map(int, open(0).read().split())) B = AB[1::2] E = [[] for _ in range(N + 1)] for a, b in zip(*[iter(AB)] * 2): E[a].append(b) Q = deque([1]) C = [0] * (N + 1) while Q: v = Q.popleft() c = 0 for u in E[v]: c += 1 + (c + 1 == C[v]) C[u] = c Q.append(u) print((max(C))) for b in B: print((C[b])) main()
p02850
from collections import deque N = int(eval(input())) EhasV = [set() for x in range(N)] EE = [0] * (N-1) for i in range(N-1): a,b = list(map(int,input().split())) a -= 1 b -= 1 EE[i] = {a,b} EhasV[a].add(i) EhasV[b].add(i) K = len(max(EhasV,key=len)) Vcolor = [set(range(1,K+1)) for x in range(N)] Ecolor = [-1] * (N-1) q = deque() q.append(0) i = 1 while i: v1 = q.pop() i -= 1 for e in EhasV[v1]: if Ecolor[e] != -1: continue color = Vcolor[v1].pop() Ecolor[e] = color edgeside = EE[e] edgeside.discard(v1) v2 = edgeside.pop() Vcolor[v2].discard(color) q.append(v2) i += 1 print(K) i = 0 while i < N - 1: print((Ecolor[i])) i += 1
from collections import deque N = int(input()) EhasV = [set() for x in range(N)] EhasVnums = [0] * N EE = [0] * (N-1) for i in range(N-1): a,b = map(int,input().split()) a -= 1 b -= 1 EE[i] = {a,b} EhasV[a].add(i) EhasV[b].add(i) EhasVnums[a] += 1 EhasVnums[b] += 1 K = len(max(EhasV,key=len)) Vcolor = [set(range(1,EhasVnums[x]+1)) for x in range(N)] Ecolor = [-1] * (N-1) q = deque() q.append(0) while q: v1 = q.pop() for e in EhasV[v1]: if Ecolor[e] != -1: continue color = Vcolor[v1].pop() Ecolor[e] = color edgeside = EE[e] edgeside.discard(v1) v2 = edgeside.pop() Vcolor[v2].discard(color) q.append(v2) print(*([K]+Ecolor),sep='\n')
p02850
import sys from collections import deque n = int(eval(input())) G = [[] for _ in range(n + 1)] G_order = [] # a<bが保証されている、aを親、bを子とする for i in range(n - 1): a, b = [int(x) - 1 for x in input().split()] G[a].append(b) G_order.append(b) # どこでも良いが、ここでは0をrootとする que = deque([0]) # 各頂点と「親」を結ぶ辺の色 # 頂点0をrootとするのでC[0]=0で確定, 他を調べる colors = [0] * n while que: # prt = 親 # 幅優先探索 prt = que.popleft() color = 0 # cld = 子 for cld in G[prt]: color += 1 # 「今考えている頂点とその親を結ぶ辺の色」と同じ色は使えない if color == colors[prt]: color += 1 colors[cld] = color que.append(cld) # それぞれの頂点とその親を結ぶ辺の色 # print(colors) # 必要な最小の色数 print((max(colors))) # 辺の番号順に色を出力 for i in G_order: print((colors[i]))
from collections import deque N = int(eval(input())) # 有向グラフと見る、G[親] = [子1, 子2, ...] G = [[] for _ in range(N + 1)] # 子ノードを記録、これで辺の番号を管理 G_order = [] # a<bが保証されている、aを親、bを子とする for i in range(N - 1): a, b = [int(x) - 1 for x in input().split()] G[a].append(b) G_order.append(b) # どこでも良いが、ここでは0をrootとする que = deque([0]) # 各頂点と「親」を結ぶ辺の色 # 頂点0をrootとするのでC[0]=0で確定(「無色」), 他を調べる colors = [0] * N # BFS while que: # prt = 親 # 幅優先探索 prt = que.popleft() color = 0 # cld = 子 for cld in G[prt]: color += 1 # 「今考えている頂点とその親を結ぶ辺の色」と同じ色は使えないので次の色にする if color == colors[prt]: color += 1 colors[cld] = color que.append(cld) # それぞれの頂点とその親を結ぶ辺の色 # print(colors) # 必要な最小の色数 print((max(colors))) # 辺の番号順に色を出力 for i in G_order: print((colors[i]))
p02850
from collections import deque N = int(eval(input())) edges = [[] for _ in range(N)] colors = [[-1 for _ in range(N)] for _ in range(N)] visited = [False] * N q = deque() def bfs(): max_cnt = 0 while q: u = q.popleft() cnt = 1 visited[u] = True for v in edges[u]: if visited[v]: continue if colors[u][v] != -1: continue while cnt in colors[u]: cnt += 1 colors[u][v] = cnt colors[v][u] = cnt q.append(v) max_cnt = max(max_cnt, cnt) return max_cnt AB = [] for _ in range(N - 1): a, b = list(map(int, input().split())) a -= 1 b -= 1 AB.append((a, b)) edges[a].append(b) edges[b].append(a) q.append(0) max_cnt = bfs() print(max_cnt) for a, b in AB: print((colors[a][b]))
import sys sys.setrecursionlimit(10 ** 7) n = int(eval(input())) A = [[] for i in range(n)] for i in range(n - 1): a, b = list(map(int, input().split())) a, b = a - 1, b - 1 A[a].append([b, i]) ans = [0] * (n - 1) def col(now, color): c = 1 for (b, j) in A[now]: if c == color: c += 1 ans[j] = c col(b, c) c += 1 col(0, 0) print((max(ans))) for a in ans: print(a)
p02850
import sys sys.setrecursionlimit(10**9) N = int(eval(input())) adjL = [[] for _ in range(N)] edges = [] for _ in range(N-1): A, B = list(map(int, input().split())) A, B = A-1, B-1 adjL[A].append(B) adjL[B].append(A) edges.append((A, B)) colors = dict() def dfs(vNow, vPar, color): c = 1 for v2 in adjL[vNow]: if v2 == vPar: continue if c == color: c += 1 A, B = vNow, v2 if A > B: A, B = B, A colors[(A, B)] = c dfs(v2, vNow, c) c += 1 dfs(0, -1, 0) #print(colors) anss = [] for A, B in edges: anss.append(colors[(A, B)]) print((max(colors.values()))) print(('\n'.join(map(str, anss))))
import sys input = sys.stdin.readline sys.setrecursionlimit(10**9) def solve(): N = int(eval(input())) adjL = [[] for _ in range(N)] for i in range(N-1): a, b = list(map(int, input().split())) a, b = a-1, b-1 adjL[a].append((b, i)) adjL[b].append((a, i)) def dfs(vNow, vPar, clrPar): clr = 1 for v2, i in adjL[vNow]: if v2 == vPar: continue if clr == clrPar: clr += 1 anss[i] = clr dfs(v2, vNow, clr) clr += 1 anss = [0] * (N-1) dfs(0, -1, 0) print((max(anss))) print(('\n'.join(map(str, anss)))) solve()
p02850
def main(): from collections import deque import sys readline = sys.stdin.buffer.readline read = sys.stdin.buffer.read N = int(readline()) R = [[int(i) for i in r.split()] for r in read().rstrip().split(b'\n')] G = [[] for _ in range(N)] edge = {} ans_key = [] for a, b in R: G[a-1].append(b-1) G[b-1].append(a-1) edge[(a-1, b-1)] = -1 ans_key.append((a-1, b-1)) max_g = max(len(g) for g in G) def bfs(s, max_g): dist = [-1 for _ in range(N)] color = [{i+1 for i in range(max_g)} for _ in range(N)] que = deque() que.append(s) dist[s] = 0 par = [-1]*N while que: u = que.popleft() if par[u] != -1: if par[u] < u: color[u].discard(edge[(par[u], u)]) else: color[u].discard(edge[(par[u], u)]) for v in G[u]: if dist[v] != -1: continue dist[v] = dist[u] + 1 que.append(v) c = color[u].pop() par[v] = u if u < v: edge[(u, v)] = c else: edge[(v, u)] = c if all(i != -1 for i in list(edge.values())): return bfs(0, max_g) print(max_g) for k in ans_key: print((edge[k])) if __name__ == '__main__': main()
def main(): import sys readline = sys.stdin.buffer.readline read = sys.stdin.buffer.read N = int(readline()) R = [[int(i) for i in r.split()] for r in read().rstrip().split(b'\n')] G = [[] for _ in range(N)] edge = {} ans_key = [] for a, b in R: G[a-1].append(b-1) G[b-1].append(a-1) edge[(a-1, b-1)] = -1 ans_key.append((a-1, b-1)) max_g = max(len(g) for g in G) def dfs(max_g): todo = [0] seen = [False]*N seen[0] = True par = [-1]*N while todo: u = todo.pop() k = 0 c = edge[(par[u], u)] if u != 0 else 0 for v in G[u]: if seen[v]: continue seen[v] = True todo.append(v) par[v] = u k += 1 if k == c: k += 1 if max_g < k: k = 1 if u < v: edge[(u, v)] = k else: edge[(v, u)] = k dfs(max_g) print(max_g) for k in ans_key: print((edge[k])) if __name__ == '__main__': main()
p02850
def main(): N = int(eval(input())) G = [[] for _ in range(N)] edge = [-1] * (N-1) for i in range(N-1): a, b = (int(i)-1 for i in input().split()) G[a].append((b, i)) G[b].append((a, i)) max_deg = max(len(G[i]) for i in range(N)) from collections import deque def bfs(s): que = deque([]) par = [-1]*N que.append(s) while que: pos = que.popleft() c = -1 k = 1 for (v, i) in G[pos]: if par[pos] == v: c = edge[i] for (v, i) in G[pos]: if par[pos] == v: continue if k == c: k += 1 par[v] = pos edge[i] = k k += 1 que.append(v) bfs(0) print(max_deg) for i in range(N-1): print((edge[i])) if __name__ == '__main__': main()
def main(): N = int(eval(input())) G = [[] for _ in range(N)] edge = [-1] * (N-1) for i in range(N-1): a, b = (int(i)-1 for i in input().split()) G[a].append(b*N + i) G[b].append(a*N + i) max_deg = max(len(G[i]) for i in range(N)) from collections import deque def bfs(s): que = deque([]) par = [-1]*N que.append(s) while que: pos = que.popleft() c = -1 k = 1 for vi in G[pos]: v, i = divmod(vi, N) if par[pos] == v: c = edge[i] for vi in G[pos]: v, i = divmod(vi, N) if par[pos] == v: continue if k == c: k += 1 par[v] = pos edge[i] = k k += 1 que.append(v) bfs(0) print(max_deg) for i in range(N-1): print((edge[i])) if __name__ == '__main__': main()
p02850
N = int(eval(input())) a,b = [],[] for _ in range(N-1): at,bt = list(map(int,input().split())) a.append(at) b.append(bt) E = [[] for _ in range(N+1)] for i in range(N-1): E[a[i]].append(b[i]) E[b[i]].append(a[i]) q = [[1,-1,0]] ans = [[0 for _ in range(N+1)] for _ in range(N+1)] cnt = 0 while q: cp, root, r_col = q.pop(0) i = 1 for np in E[cp]: if np == root: continue if i == r_col: i += 1 q.append([np,cp,i]) ans[cp][np] = i ans[np][cp] = i cnt = max(cnt, i) i += 1 print(cnt) for i in range(N-1): print((ans[a[i]][b[i]]))
N = int(eval(input())) E = sorted([list(map(int, input().split())) + [i] for i in range(N-1)], key = lambda x:x[1]) E.sort() ans = [0 for _ in range(N-1)] flg = [0 for _ in range(N+1)] t = 0 cnt = 0 ans_a = 0 for i in range(N-1): a,b,ind = E[i] if t != a: cnt = 1 t = a if flg[a] == cnt: cnt += 1 ans[ind] = cnt flg[b] = cnt ans_a = max(ans_a, cnt) cnt += 1 print(ans_a) for a in ans: print(a)
p02850
from collections import deque n = int(input()) graph = [[] for _ in range(n)] edge = [] for i in range(n-1): a, b = map(lambda x:int(x)-1, input().split()) edge.append({a,b}) graph[a].append(b) graph[b].append(a) k = max(len(i) for i in graph) que = deque() seen = [False]*n ans = [0]*(n-1) que.append((0, -1)) while len(que)>0: node, p_color = que.popleft() seen[node] = True color = 1 for i in graph[node]: if seen[i]: continue if color==p_color: color += 1 ans[edge.index({node,i})] = color que.append((i, color)) color += 1 print(k) [print(i) for i in ans]
import sys n = int(input()) sys.setrecursionlimit(2*n) graph = [[] for _ in range(n)] for i in range(n-1): a, b = map(lambda x:int(x)-1, input().split()) graph[a].append((b, i)) graph[b].append((a, i)) def DFS(node, p_node=-1, p_color=-1): color = 1 for c_node, edge in graph[node]: if c_node==p_node: continue if color==p_color: color += 1 ans[edge] = color DFS(c_node, node, color) color += 1 ans = [0]*(n-1) DFS(0) k = max(len(i) for i in graph) print(k) [print(i) for i in ans]
p02850
N = int(eval(input())) G = [[] for i in range(N)] for i in range(N-1): a, b = list(map(int, input().split())) G[a-1].append((b-1, i)) v_color = [0] * N e_color = [0] * (N-1) K = 1 for a, children in enumerate(G): c = 1 for b, i in children: if c == v_color[a]: c += 1 v_color[b] = c e_color[i] = c K = max(K, c) c += 1 print(K) print(('\n'.join(map(str, e_color))))
def main(): n = int(eval(input())) # G = [[0] * (n-1) for i in range(2)] cnt = [0] * n G = [[] for i in range(n)] for i in range(n-1): a, b = list(map(int, input().split())) G[a-1].append((b-1, i)) cnt[a-1] += 1 cnt[b-1] += 1 # for i in range(n-1): # a,b = map(int, input().split()) # G[0][i] = a-1 # G[1][i] = b-1 # cnt[a-1] += 1 # cnt[b-1] += 1 num = 0 # print(G) print((max(cnt))) tmp_clr = [0] * (n-1) tmp_edge = [0] * n # print(G) for frm, child in enumerate(G): clr = 1 for j, to in enumerate(child): if tmp_edge[frm] == clr : clr += 1 tmp_clr[to[1]] = clr # tmp_edge[frm] = clr tmp_edge[to[0]] = clr clr+=1 # print(tmp_edge) # print(tmp_clr) print(('\n'.join(map(str, tmp_clr)))) if __name__=='__main__': main()
p02850
# 深さ優先探索 from sys import setrecursionlimit def genid(a, b): if b < a: a, b = b, a return a * 100000 + b N = int(eval(input())) ab = [list(map(int, input().split())) for _ in range(N - 1)] edges = [[] for _ in range(N)] for a, b in ab: edges[a - 1].append(b - 1) edges[b - 1].append(a - 1) colors = {} q = [(0, -1, -1)] while q: currentNode, usedColor, parentNode = q.pop() color = 1 for childNode in edges[currentNode]: if childNode == parentNode: continue if color == usedColor: color += 1 colors[genid(currentNode, childNode)] = color q.append((childNode, color, currentNode)) color += 1 print((max(len(e) for e in edges))) for a, b in ab: print((colors[genid(a - 1, b - 1)]))
# 深さ優先探索 from sys import setrecursionlimit def genid(a, b): if b < a: a, b = b, a return a * 100000 + b def paint(currentNode, usedColor, parentNode, edges, colors): color = 1 for childNode in edges[currentNode]: if childNode == parentNode: continue if color == usedColor: color += 1 colors[genid(currentNode, childNode)] = color paint(childNode, color, currentNode, edges, colors) color += 1 setrecursionlimit(10 ** 6) N = int(eval(input())) ab = [list(map(int, input().split())) for _ in range(N - 1)] edges = [[] for _ in range(N)] for a, b in ab: edges[a - 1].append(b - 1) edges[b - 1].append(a - 1) colors = {} paint(0, -1, -1, edges, colors) print((max(len(e) for e in edges))) for a, b in ab: print((colors[genid(a - 1, b - 1)]))
p02850
# coding: utf-8 # Your code here! import sys sys.setrecursionlimit(10**9) N = int(eval(input())) graph = [[] for i in range(N)] for i in range(N-1): a,b = list(map(int,input().split())) graph[a-1].append((b,i)) graph[b-1].append((a,i)) ans = [0]*(N-1) ten_col =[[] for i in range(N)] def dfs(start,now): new_col = 1 for (future,i) in graph[now-1]: if future == start: pass else: if new_col in ten_col[now-1]: new_col += 1 ten_col[now-1].append(new_col) ten_col[future-1].append(new_col) ans[i] = new_col new_col += 1 dfs(now,future) dfs(-1,1) print((max(ans))) for i in ans: print(i)
import sys sys.setrecursionlimit(10**9) N = int(eval(input())) graph = [[] for i in range(N)] for i in range(N-1): a,b = list(map(int,input().split())) graph[a-1].append((b,i)) graph[b-1].append((a,i)) ans = [0]*(N-1) def dfs(past,now,edge_col): new_col = 1 for (future,i) in graph[now-1]: if future == past: pass else: if new_col == edge_col: new_col += 1 ans[i] = new_col dfs(now,future,new_col) new_col += 1 dfs(-1,1,-1) print((max(ans))) for i in ans: print(i)
p02850
# Problem D - Coloring Edges on Tree from collections import deque # input N = int(eval(input())) node_list = {} # 隣接リストの作成 color_count_list = [0]*(N+1) ans_list = [] for i in range(N-1): a, b = list(map(int, input().split())) if a in node_list: node_list[a].append(b) else: node_list[a] = [b] color_count_list[a] += 1 color_count_list[b] += 1 ans_list.append([a, b]) # initialization color_list = [[0]*(N+1) for i in range(N+1)] color_max_count = max(color_count_list) # bfs search visit_queue = deque([[-1, 1]]) # [[既に使った色], 遷移ノード] while len(visit_queue)>0: p = visit_queue.popleft() used_color = p[0] if p[1] in node_list: nodes = node_list[p[1]] nodes_len = len(nodes) color_num = 1 if nodes_len>=1: coloring_count = 0 while coloring_count<nodes_len: if color_num==used_color: color_num += 1 continue color_list[p[1]][nodes[coloring_count]] = color_num color_list[nodes[coloring_count]][p[1]] = color_num # queue insert visit_queue.append([color_num, nodes[coloring_count]]) # color update coloring_count += 1 color_num += 1 # output print(color_max_count) for a in ans_list: print((color_list[a[0]][a[1]]))
from collections import deque n=int(eval(input())) G=[[]for _ in range(n)] L=[] ans=[0]*n for i in range(n-1): a,b=list(map(int,input().split())) G[a-1].append(b-1) L.append(b-1) que=deque([0]) while que: s=que.pop() color=1 for ni in G[s]: if ans[s]==color: color+=1 ans[ni]=color color+=1 que.append(ni) print((max(ans))) for i in L: print((ans[i]))
p02850
#!/usr/bin/env python3 import sys sys.setrecursionlimit(10**9) input = sys.stdin.readline n = int(eval(input())) edge = [[] for _ in [0]*n] for i in range(~-n): a, b = list(map(int, input().split())) a -= 1;b -= 1 edge[a] += [[b, i]] ans = [0] * ~-n def dfs(now, color): count = 1 for to, i in edge[now]: # 親の色と同じとき if count == color: count += 1 ans[i] = count dfs(to, count) count += 1 # 開始根は0番目に dfs(0, 0) print((max(ans))) for p in ans: print(p)
import sys sys.setrecursionlimit(10**9) input = sys.stdin.readline n = int(eval(input())) edge = [[] for _ in [0]*n] for i in range(~-n): a, b = list(map(int, input().split())) a -= 1;b -= 1 edge[a] += [[b, i]] ans = [0] * ~-n def dfs(now, color): count = 1 for to, i in edge[now]: # 親の色と同じとき if count == color: count += 1 ans[i] = count dfs(to, count) count += 1 # 開始根は0番目に dfs(0, 0) print((max(ans))) for p in ans: print(p)
p02850
# 色の最大は辺が一番多い頂点 # 各頂点が現在持ってる色を覚える -> 2次元配列 : color_num = [[]*N] # 答えを出力するための部分 -> 2次元配列 : ans = [[] * N for _ in range(N)] # 答えの出し方はN-1ループでa[i], b[i]をansにいれる from collections import deque N = int(eval(input())) graph = [[] for _ in range(N)] AB = [[0] * 2 for _ in range(N-1)] for i in range(N-1): a, b = list(map(int, input().split())) a -= 1 b -= 1 graph[a].append(b) graph[b].append(a) AB[i][0], AB[i][1] = a, b K = 0 for i in range(N-1): K = max(len(graph[i]), K) # BFSのためのデータ構造 que = deque() dist = [False] * N # 初期条件 que.append(0) color_num = [[0] * N for _ in range(N)] dist[0] = True # BFS開始 while que: v = que[0] que.popleft() tmp = 0 for new_v in graph[v]: if dist[new_v]: continue # 新たな頂点 new_vについて距離情報を更新してキューを追加する dist[new_v] = True que.append(new_v) # 色を塗る for k in range(tmp+1, K+1): if k in color_num[v]: continue else: color_num[v][new_v] = k color_num[new_v][v] = k tmp = k break # 答えの出力 print(K) for i in range(N-1): print((color_num[AB[i][0]][AB[i][1]]))
# 色の最大は辺が一番多い頂点 # 各頂点が現在持ってる色を覚える -> 2次元配列 : color_num = [[]*N] # 答えを出力するための部分 -> 2次元配列 : ans = [[] * N for _ in range(N)] # 答えの出し方はN-1ループでa[i], b[i]をansにいれる from collections import deque N = int(eval(input())) graph = {i:[] for i in range(N)} AB = [[0] * 2 for _ in range(N-1)] for i in range(N-1): a, b = list(map(int, input().split())) a -= 1 b -= 1 graph[a].append(b) graph[b].append(a) AB[i][0], AB[i][1] = a, b if i == 0: start = a K = 0 for some in list(graph.values()): K = max(len(some), K) # BFSのためのデータ構造 que = deque() dist = [False] * N # 初期条件 que.append(start) color_num = {i:{} for i in range(N)} dist[start] = True # BFS開始 while que: v = que[0] que.popleft() tmp = 0 for new_v in graph[v]: if dist[new_v]: continue # 新たな頂点 new_vについて距離情報を更新してキューを追加する dist[new_v] = True que.append(new_v) # 色を塗る for k in range(tmp+1, K+1): if k in list(color_num[v].values()): continue else: color_num[v][new_v] = k color_num[new_v][v] = k tmp = k break # 答えの出力 print(K) for i in range(N-1): print((color_num[AB[i][0]][AB[i][1]]))
p02850
import sys input = sys.stdin.readline n = int(eval(input())) routes = [] ans = [[0]*n for i in range(n)] edges = [[]for _ in range(n)] used = [0]*n for i in range(n-1): a, b = list(map(int, input().split())) routes.append([a-1, b-1]) edges[a-1].append(b-1) sort_routes = sorted(routes) for node in range(n): unanle = used[node] count = 1 if count == unanle: count += 1 for to in edges[node]: ans[node][to] = count used[to] = count count += 1 if count == unanle: count += 1 print((max(used))) for _from, to in routes: print((ans[_from][to]))
import sys input = sys.stdin.readline n = int(eval(input())) routes = [] dic = [{}] * n edges = [[]for _ in range(n)] used = [0]*n for i in range(n-1): a, b = list(map(int, input().split())) routes.append([a-1, b-1]) edges[a-1].append(b-1) for node in range(n): unanle = used[node] count = 1 if count == unanle: count += 1 for to in edges[node]: dic[node][to] = count used[to] = count count += 1 if count == unanle: count += 1 print((max(used))) for _from, to in routes: print((dic[_from][to]))
p02850
#!/usr/bin/env python3 import sys sys.setrecursionlimit(100000) def main(): N = int(eval(input())) sides = [[] for _ in range(N-1)] for i in range(N-1): a,b = list(map(int, input().split())) sides[a-1].append((b-1,i)) ans = [[None] for _ in range(N-1)] def dfs(focus,parent_color): color = 1 for child,index in sides[focus]: if parent_color == color: color += 1 #もし親の色と被っていた場合はその色を飛ばす ans[index] = color if child < N-1: dfs(child,color) color += 1 #同じ親から続く次の辺の色を変更する dfs(0,0) print((max(ans))) for color in ans: print(color) if __name__ == "__main__": main()
#!/usr/bin/env python3 import sys sys.setrecursionlimit(100000) def main(): N = int(eval(input())) sides = [[] for _ in range(N-1)] for i in range(N-1): a,b = list(map(int, input().split())) sides[a-1].append((b-1,i)) ans = [[None] for _ in range(N-1)] def dfs(focus,parent_color): if focus == N-1: return color = 1 for child,index in sides[focus]: if parent_color == color: color += 1 #もし親の色と被っていた場合はその色を飛ばす ans[index] = color # if child < N-1: # dfs(child,color) dfs(child,color) color += 1 #同じ親から続く次の辺の色を変更する dfs(0,0) print((max(ans))) for color in ans: print(color) if __name__ == "__main__": main()
p02850
import sys input = sys.stdin.readline n = int(eval(input())) degree = [ 0 for i in range(n) ] connect_list = [ [] for i in range(n) ] node_color = [0 for i in range(n)] for i in range(n-1): a, b = [ int(v)-1 for v in input().split() ] connect_list[a].append([b,i]) degree[a] += 1 degree[b] += 1 maxcolor = max(degree) search_list = [0] node_color[0] = 0 while search_list: new_search_list = [] for i in search_list: if node_color[i] == 0: color_list = [ k for k in range(1,maxcolor+1) ] else: color_list = [ k for k in range(1,maxcolor+1) if k != node_color[i] ] p = 0 for j, v in enumerate(connect_list[i]): a, b = v new_search_list.append(a) node_color[a] = color_list[p] connect_list[i][j] = [b,color_list[p]] p += 1 search_list = new_search_list ans_list = [] for i in connect_list: for j in i: ans_list.append(j) ans_list.sort() print(maxcolor) for i in ans_list: print((i[1]))
import sys input = sys.stdin.readline n = int(eval(input())) degree = [ 0 for i in range(n) ] connect_list = [ [] for i in range(n) ] node_color = [0 for i in range(n)] for i in range(n-1): a, b = [ int(v)-1 for v in input().split() ] connect_list[a].append([b,i]) degree[a] += 1 degree[b] += 1 maxcolor = max(degree) search_list = [0] node_color[0] = 0 color_list = [ k for k in range(1,maxcolor+1) ] while search_list: new_search_list = [] for i in search_list: p = 0 for j, v in enumerate(connect_list[i]): a, b = v new_search_list.append(a) if node_color[i] == color_list[p]: p += 1 node_color[a] = color_list[p] connect_list[i][j] = [b,color_list[p]] p += 1 search_list = new_search_list ans_list = [] for i in connect_list: for j in i: ans_list.append(j) ans_list.sort() print(maxcolor) for i in ans_list: print((i[1]))
p02850
import sys from collections import deque input = sys.stdin.readline N = int(eval(input())) D = [[0] * N for n in range(N)] maxi = -1 AB = [0] * (N-1) for n in range(N-1): a, b = tuple([int(x) for x in input().strip().split()]) AB[n] = (a, b) D[a-1][b-1] = '#' D[b-1][a-1] = '#' maxc = 0 for i, d in enumerate(D): c = d.count('#') if c > maxc: maxc = c maxi = i q = deque([]) c = 1 for i in range(N): if D[maxi][i] == '#': D[maxi][i] = c D[i][maxi] = c c += 1 q.append(i) while q: ind = q.popleft() c = 1 for i in range(N): while c in D[ind]: c += 1 if D[ind][i] == '#': D[ind][i] = c D[i][ind] = c c += 1 if i not in q: q.append(i) print(maxc) for a, b in AB: print((D[a-1][b-1]))
import sys from collections import deque input = sys.stdin.readline N = int(eval(input())) D = [deque([]) for _ in range(N)] MAP = [[0] * N for n in range(N)] maxi = -1 AB = [0] * (N-1) for n in range(N-1): a, b = [int(x) for x in input().strip().split()] AB[n] = (a, b) D[a-1].append(b-1) D[b-1].append(a-1) maxc = 0 for i, d in enumerate(D): c = len(d) if c > maxc: maxc = c maxi = i C = [[0] * maxc for _ in range(N)] for n in D[maxi]: #print('max index = {}, next node = {}'.format(maxi, n)) MAP[maxi][n] = c MAP[n][maxi] = c C[maxi][c-1] = 1 C[n][c-1] = 1 c += 1 print(maxc) for a, b in AB: if a-1 == maxi or b-1 == maxi: print((MAP[a-1][b-1])) for i in range(maxc): if C[a-1][i] == 0 and C[b-1][i] == 0: print((i+1)) C[a-1][i] = 1 C[b-1][i] = 1 break
p02850
import sys from collections import deque input = sys.stdin.readline N = int(eval(input())) D = [deque([]) for _ in range(N)] MAP = [[0] * N for n in range(N)] maxi = -1 AB = [0] * (N-1) for n in range(N-1): a, b = [int(x) for x in input().strip().split()] AB[n] = (a, b) D[a-1].append(b-1) D[b-1].append(a-1) maxc = 0 for i, d in enumerate(D): c = len(d) if c > maxc: maxc = c maxi = i C = [[0] * maxc for _ in range(N)] for n in D[maxi]: #print('max index = {}, next node = {}'.format(maxi, n)) MAP[maxi][n] = c MAP[n][maxi] = c C[maxi][c-1] = 1 C[n][c-1] = 1 c += 1 print(maxc) for a, b in AB: if a-1 == maxi or b-1 == maxi: print((MAP[a-1][b-1])) for i in range(maxc): if C[a-1][i] == 0 and C[b-1][i] == 0: print((i+1)) C[a-1][i] = 1 C[b-1][i] = 1 break
import sys from collections import deque input = sys.stdin.readline sys.setrecursionlimit(100000) N = int(eval(input())) D = [deque([]) for _ in range(N)] cnt = 0 AB = [0] * (N-1) dic = {} for n in range(N-1): a, b = [int(x) for x in input().strip().split()] AB[n] = (a-1, b-1) dic[(a, b)] = 0 D[a-1].append(b-1) D[b-1].append(a-1) print((max([len(d) for d in D]))) def dp(pp, p, c): global dic nc = 1 for np in D[p]: if np == pp: continue if nc == c: nc += 1 dic[(p, np)] = nc dp(p, np, nc) nc += 1 return 0 dp(-1, 0, 0) for ab in AB: print((dic[ab]))
p02850
from collections import deque import sys input = sys.stdin.readline n = int(eval(input())) g = [[] for i in range(n)] l = [0] * (n-1) for _ in range(n-1): a,b = list(map(int,input().split())) a,b = a-1,b-1 l[_] = (min(a,b),max(a,b)) g[a].append(b) g[b].append(a) m = 0 for _ in range(n): if len(g[_]) > m: m = len(g[_]) mi = _ print(m) g2 = [set(range(1,m+1)) for i in range(n)] deq = deque([mi]) vi = [0] * n vi[mi] = 1 d = dict() while deq: cur = deq.popleft() for i in g[cur]: if vi[i] == 1: continue else: vi[i] = 1 deq.append(i) cu = (g2[cur]&g2[i]).pop() g2[cur].discard(cu) g2[i].discard(cu) d[(min(cur,i),max(cur,i))] = cu for i in l: print((d[i]))
import sys input = sys.stdin.readline n = int(eval(input())) g = [[] for i in range(n)] l = [0] * (n-1) for _ in range(n-1): a,b = list(map(int,input().split())) a,b = a-1,b-1 l[_] = (min(a,b),max(a,b)) g[a].append(b) g[b].append(a) m = 0 for _ in range(n): if len(g[_]) > m: m = len(g[_]) mi = _ print(m) g2 = [[] for i in range(n)] stack = [(mi,-1)] vi = [0] * n vi[mi] = 1 d = dict() while stack: pre,prei = stack.pop() c = 0 for i in g[pre]: if vi[i] == 1: continue else: vi[i] = 1 c += 1 if c == prei: c += 1 d[(min(pre,i),max(pre,i))] = c stack.append((i,c)) for i in l: print((d[i]))
p02850
from collections import deque def main(): n = int(eval(input())) ab = [] colors = [[-1 for _ in range(n)] for _ in range(n)] visit = [-1 for _ in range(n)] tree = [[] for _ in range(n)] for i in range(n-1): a, b = list(map(int,input().split())) ab.append([a-1, b-1]) tree[a-1].append(b-1) tree[b-1].append(a-1) visit[0]=0 q = deque([0]) while q: s = q.pop() d = 0 for i in tree[s]: if visit[i]<0: d += 1 + (1+d==visit[s]) visit[i] = d q.append(i) print((max(visit))) for a, b in ab: print((visit[b])) if __name__=="__main__": main()
from collections import deque def main(): n = int(eval(input())) ab = [] visit = [-1 for _ in range(n+1)] tree = [[] for _ in range(n+1)] for i in range(n-1): a, b = list(map(int,input().split())) ab.append([a, b]) tree[a].append(b) tree[b].append(a) visit[1]=0 q = deque([1]) while q: s = q.pop() d = 0 for i in tree[s]: if visit[i]<0: d += 1 + (1+d==visit[s]) visit[i] = d q.append(i) print((max(visit))) for a, b in ab: print((visit[b])) if __name__=="__main__": main()
p02850
import sys sys.setrecursionlimit(4100000) N = int(eval(input())) tree = [[] for _ in range(N+1) ] already_make = [-1]*(N+1) for i in range(1,N): a,b = list(map(int,input().split(' '))) tree[a].append([b,i]) last_color = 0 bfs_use_coler = [[] for _ in range(N+1)] def solve(n,last_color): ''' use_colers =[] for val in bfs_use_coler[0:n-2]: use_colers = use_colers + val ''' for val in tree[n]: if already_make[val[1]] != -1: continue use_coloer = -1 length = last_color+1 a_tree = list(set(list(range(1,length))) - set(bfs_use_coler[val[0]]) ) b_tree = list(set(list(range(1,length))) - set(bfs_use_coler[n])) ab_tree = list(set(a_tree)& set(b_tree)) ''' for i in range(1,length): if i in bfs_use_coler[val[0]] or i in bfs_use_coler[n]: continue else: use_coloer = i break if use_coloer == -1: last_color +=1 use_coloer = last_color ''' if len(ab_tree) > 0: use_coloer = ab_tree[0] else: last_color +=1 use_coloer = last_color bfs_use_coler[val[0]].append(use_coloer) bfs_use_coler[n].append(use_coloer) already_make[val[1]] = use_coloer return last_color for i in range(1,N+1): last_color = solve(i,last_color) print(last_color) for val in already_make[1:N]: print(val)
import sys sys.setrecursionlimit(4100000) N = int(eval(input())) tree = [[] for _ in range(N+1) ] already_make = [-1]*(N+1) for i in range(1,N): a,b = list(map(int,input().split(' '))) tree[a].append([b,i]) last_color = 0 #bfs_use_coler = [[ -1 for _ in range(N+1) ] for _ in range(N+1) ] def solve_bfs(previous_colors,n_list,last_color): ''' use_colers =[] for val in bfs_use_coler[0:n-2]: use_colers = use_colers + val ''' next_colors = [] next_n_list =[] for idx1,n in enumerate(n_list): use_color_num = 1 for idx2,val in enumerate(tree[n]): if use_color_num == previous_colors[idx1]: use_color_num += 1 already_make[val[1]] = use_color_num next_colors.append(use_color_num) next_n_list.append(val[0]) last_color = max(use_color_num,last_color) use_color_num += 1 if len(next_colors) > 0: return solve_bfs(next_colors,next_n_list,last_color) else: return last_color last_color = solve_bfs([0],[1],last_color) print(last_color) for val in already_make[1:N]: print(val)
p02850
import sys sys.setrecursionlimit(2147483647) INF=float("inf") MOD=10**9+7 input=lambda :sys.stdin.readline().rstrip() def resolve(): n=int(input()) E=[[] for _ in range(n)] idx={} for i in range(n-1): a,b=map(int,input().split()) a-=1; b-=1 E[a].append(b) E[b].append(a) idx[(min(a,b),max(a,b))]=i ans=[None]*(n-1) def dfs(v=0,p=-1,c=0): col=1 for nv in E[v]: col+=col==c if(nv==p): continue ans[idx[(min(v,nv),max(v,nv))]]=col dfs(nv,v,col) col+=1 dfs() print(max(ans)) print(*ans,sep='\n') resolve()
import sys sys.setrecursionlimit(2147483647) INF=float("inf") MOD=10**9+7 input=lambda:sys.stdin.readline().rstrip() def resolve(): n=int(input()) E=[[] for _ in range(n)] idx={} for i in range(n-1): a,b=map(int,input().split()) a-=1; b-=1 E[a].append(b) E[b].append(a) idx[(a,b)]=i idx[(b,a)]=i k=max(len(E[i]) for i in range(n)) # dfs ans=[None]*(n-1) Q=[(0,-1)] while(Q): v,p=Q.pop() # 根のとき -> 辺を張る if(p==-1): col=1 for nv in E[v]: ans[idx[(v,nv)]]=col col+=1 Q.append((nv,v)) # そうでないとき -> 親の色は除外 else: col=1 for nv in E[v]: if(nv==p): continue col+=(col==ans[idx[(v,p)]]) # 親の色になってしまったら足す ans[idx[(v,nv)]]=col col+=1 Q.append((nv,v)) print(k) print(*ans,sep='\n') resolve()
p02850
from collections import Counter, defaultdict from queue import Queue G = defaultdict(list) C = Counter() N = int(eval(input())) ans = {} o = [] for i in range(N-1): a, b = list(map(int, input().split())) C[a] += 1 C[b] += 1 G[a].append(b) G[b].append(a) ans[(a, b)] = 0 o.append((a,b)) cs = [0] * (N+1) def bfs(v): ret = 0 visited = set() q = Queue() visited.add(v) q.put(v) while not q.empty(): v = q.get() counter = 1 for c in G[v]: if not c in visited: visited.add(c) if counter == cs[v]: counter += 1 cs[c] = ans[(c,v)] = ans[(v,c)] = counter counter += 1 q.put(c) bfs(1) print((C.most_common(1)[0][1])) for a,b in o: print((ans[(a,b)]))
from collections import Counter, defaultdict from sys import getrecursionlimit,setrecursionlimit setrecursionlimit(100*getrecursionlimit()) G = defaultdict(list) C = Counter() N = int(eval(input())) ans = {} o = [] for i in range(N-1): a, b = list(map(int, input().split())) C[a] += 1 C[b] += 1 G[a].append(b) G[b].append(a) ans[(a, b)] = 0 o.append((a,b)) a = C.most_common(1)[0][0] b = C.most_common(1)[0][1] visited = [False] * (N+1) def dfs(v, p): visited[v] = True counter = 1 for c in G[v]: if not visited[c]: if p != 0 and counter == ans[(v, p)]: counter += 1 ans[(v, c)] = ans[(c, v)] = counter counter += 1 dfs(c, v) dfs(a, 0) print(b) for a,b in o: print((ans[(a,b)]))
p02850
# -*- coding: utf-8 -*- from collections import deque n = int(eval(input())) edges = [list(map(int, input().split())) for i in range(n-1)] # 使われていない色を保持する nodes = [deque([i for i in range(1, n)]) for j in range(n)] tree = {} for edge in sorted(edges): a = edge[0] # 頂点a b = edge[1] # 頂点b color = nodes[a-1].popleft() tree[(a, b)] = color nodes[b-1].remove(color) print((max(tree.values()))) for edge in edges: a = edge[0] # 頂点a b = edge[1] # 頂点b print((tree[(a, b)]))
# -*- coding: utf-8 -*- from collections import deque n = int(eval(input())) edges = [list(map(int, input().split())) for i in range(n-1)] tree = {} node_in = [0 for i in range(n)] # 頂点に入る辺は1つ node_out = [[0] for i in range(n)] # 頂点から出る辺は1つ以上 for edge in sorted(edges): a = edge[0] # 頂点a b = edge[1] # 頂点b color = 0 if node_out[a-1][-1] == 0: if node_in[a-1] <= 1: # node_in[a-1] == 0の時1、1の時2なのでまとめて color = node_in[a-1] + 1 else: # node_in[a-1] >= 2 color = 1 else: color = node_out[a-1][-1] + 1 if node_in[a-1] == color: color += 1 tree[(a, b)] = color node_out[a-1].append(color) node_in[b-1] = color print((max(tree.values()))) for edge in edges: a = edge[0] # 頂点a b = edge[1] # 頂点b print((tree[(a, b)]))
p02850
n=int(eval(input())) l=[list(map(int,input().split()))+[i] for i in range(n-1)] l.sort() #print(l) aa=[[] for _ in range(n)] #aa[l[0][0]-1].append(1) def bfs(v): d=[-1]*n d[v]=0 q=[v] c=1 #print(d,q) while q: q1=[] for i in q: for j in pt[i]: if d[j]==-1: d[j]=c q1.append(j) for k in range(1,n): if k not in set(aa[i]) and k not in set(aa[j]): aa[j].append(k) aa[i].append(k) break q=q1 c+=1 #print(aa,d,q) return d pt=[[] for _ in range(n)] for i in range(n-1): pt[l[i][0]-1].append(l[i][1]-1) pt[l[i][1]-1].append(l[i][0]-1) #print(pt) ans=bfs(l[0][0]-1) #print(aa) A=0 for i in range(n): A=max(A,max(aa[i])) print(A) for i in range(n-1): #print(aa) #print(aa[l[i][0]-1][0]) l[i].append(aa[l[i][0]-1][0]) aa[l[i][0]-1]=aa[l[i][0]-1][1:] aa[l[i][1]-1]=aa[l[i][1]-1][1:] l=sorted(l, key=lambda x: x[2]) for i in range(n-1): print((l[i][3]))
n = int(eval(input())) l=[list(map(int,input().split()))+[i+1] for i in range(n-1)] l.sort() flg = [0 for _ in range(n+1)] ans = [0 for _ in range(n)] #print(l) t=0 count=0 for i in range(n-1): a,b,c=l[i] if t!=a: t=a count=1 if flg[a]==count: count+=1 flg[b]=count ans[c]=count count+=1 #print(flg,ans) print((max(flg))) for i in range(1,n): print((ans[i]))
p02850
N=int(eval(input())) edge=[tuple(i for i in list(map(int,input().split(" ")))) for i in range(N-1)] graph=[set(i for i in range(1,N+1)) for j in range(N+1)] a_list=[] for i,j in edge: ans = graph[i]&graph[j] a_list.append(min(ans)) graph[i].remove(min(ans)) graph[j].remove(min(ans)) print((max(a_list))) for i in a_list: print(i)
N=int(eval(input())) edge=[tuple(i for i in list(map(int,input().split(" ")))) for i in range(N-1)] graph=[[i for i in range(1,N+1)] for j in range(N+1)] a_list=[] for i,j in edge: ans = set(graph[i])&set(graph[j]) tmp=min(ans) a_list.append(tmp) graph[i].remove(tmp) graph[j].remove(tmp) print((max(a_list))) for i in a_list: print(i)
p02850
N=int(eval(input())) edge=[tuple(i for i in list(map(int,input().split(" ")))) for i in range(N-1)] graph=[[i for i in range(1,N+1)] for j in range(N+1)] a_list=[] for i,j in edge: ans = set(graph[i])&set(graph[j]) tmp=min(ans) a_list.append(tmp) graph[i][tmp-1]=N+1 graph[j][tmp-1]=N+1 print((max(a_list))) for i in a_list: print(i)
import sys sys.setrecursionlimit(500000) N = int(eval(input())) E = [[] for i in range(N + 1)] for i in range(N - 1): a, b = list(map(int, input().split(' '))) E[a].append((b, i)) E[b].append((a, i)) K = max(len(e) for e in E) print(K) ans = [-1] * (N - 1) def dfs(v=1, p=0, p_col=-1): col = 1 for u, idx in E[v]: if u != p: if col == p_col: col += 1 ans[idx] = col dfs(u, v, col) col += 1 dfs() for i in ans: print(i)
p02850
#!/usr/bin/env pypy3 import sys # import math # import re # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s) from collections import deque # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate() # from collections import defaultdict # subclass of dict. defaultdict(facroty) # from collections import Counter # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter) # from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn). # from heapq import nlargest, nsmallest # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn). # from itertools import product # product(iter, repeat=n) # from itertools import accumulate # accumulate(iter[, f]) # from functools import reduce # reduce(f, iter[, init]) # from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]). # from fractions import gcd # for Python3.4.3 def main(): mod = 10000007 # 10^9+7 inf = float('inf') input = sys.stdin.readline # 改行文字が残ることに注意 sys.setrecursionlimit(10**6) # 1000 -> 1000000 def ii(): return int(eval(input())) def mi(): return list(map(int, input().rstrip().split())) def lmi(): return list(map(int, input().rstrip().split())) def li(): return list(input().rstrip()) def bfs_tree_traverse(start): paths = deque([[start]]) max_branch = 0 while paths: # print(paths) current_path = paths.popleft() u = current_path[-1] previous = current_path[-2] if len(current_path)>=2 else -1 previous_color = color[current_path[-2]][u] if len(current_path)>=2 else 0 count = 0 # 現在の頂点 u から伸びるリンクの数を数える current_color = 0 for v in adj[u]: count += 1 # 親へのリンクも含めて数えている if v != previous: tmp = current_path[:] tmp.append(v) paths.append(tmp) current_color += 1 if current_color == previous_color: current_color += 1 color[u][v] = current_color color[v][u] = current_color max_branch = max(max_branch, count) return max_branch n = ii() adj = [[] for _ in range(n)] L = [list([int(x)-1 for x in input().rstrip().split()]) for _ in range(n-1)] for pair in L: a, b = pair adj[a].append(b) adj[b].append(a) color = [[None] * n for _ in range(n)] print((bfs_tree_traverse(0))) for pair in L: a, b = pair print((color[a][b])) if __name__ == "__main__": main()
#!/usr/bin/env pypy3 import sys # import math # import re # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s) from collections import deque # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate() # from collections import defaultdict # subclass of dict. defaultdict(facroty) # from collections import Counter # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter) # from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn). # from heapq import nlargest, nsmallest # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn). # from itertools import product # product(iter, repeat=n) # from itertools import accumulate # accumulate(iter[, f]) # from functools import reduce # reduce(f, iter[, init]) # from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]). # from fractions import gcd # for Python3.4.3 def main(): mod = 10000007 # 10^9+7 inf = float('inf') input = sys.stdin.readline # 改行文字が残ることに注意 sys.setrecursionlimit(10**6) # 1000 -> 1000000 def ii(): return int(eval(input())) def mi(): return list(map(int, input().rstrip().split())) def lmi(): return list(map(int, input().rstrip().split())) def li(): return list(input().rstrip()) def bfs_tree_traverse(start): paths = deque([[start]]) max_branch = 0 while paths: # print(paths) current_path = paths.popleft() u = current_path[-1] previous = current_path[-2] if len(current_path)>=2 else -1 previous_color = color[current_path[-2]][u] if len(current_path)>=2 else 0 count = 0 # 現在の頂点 u から伸びるリンクの数を数える current_color = 0 for v in adj[u]: count += 1 # 親へのリンクも含めて数えている if v != previous: # tmp = current_path[:] tmp = current_path[-1:] # 定数倍高速化への道のり tmp.append(v) paths.append(tmp) current_color += 1 if current_color == previous_color: current_color += 1 color[u][v] = current_color # color[v][u] = current_color # 定数倍高速化への道のり max_branch = max(max_branch, count) return max_branch n = ii() adj = [[] for _ in range(n)] L = [list([int(x)-1 for x in input().rstrip().split()]) for _ in range(n-1)] for pair in L: a, b = pair adj[a].append(b) adj[b].append(a) color = [[None] * n for _ in range(n)] print((bfs_tree_traverse(0))) for pair in L: a, b = pair print((color[a][b])) if __name__ == "__main__": main()
p02850
import sys sys.setrecursionlimit(10**6) N = int(eval(input())) P = [[] for _ in range(N + 1)] P2 = [[0] * (N + 1) for _ in range(N + 1)] AB = [] for _ in range(N - 1): a, b = [int(_) for _ in input().split()] P[a].append(b) P[b].append(a) AB.append((a,b)) C = 0 for p in P: if len(p) > C: C = len(p) def f(n, pre, used): c = 1 for i, next_n in enumerate(P[n]): if pre == next_n: continue if c == used: c += 1 P2[n][next_n] = c P2[next_n][n] = c f(next_n, n, c) c += 1 print(C) f(1, -1, 0) # print(P2) for a,b in AB: print((P2[a][b]))
import sys sys.setrecursionlimit(10**6) N = int(eval(input())) P = [[] for _ in range(N + 1)] AB = [] for _ in range(N - 1): a, b = [int(_) for _ in input().split()] P[a].append(b) P[b].append(a) AB.append((a,b)) C = 0 for p in P: if len(p) > C: C = len(p) P2 = dict() def f(n, pre, used): c = 1 for i, next_n in enumerate(P[n]): if pre == next_n: continue if c == used: c += 1 # P2[n][next_n] = c # P2[next_n][n] = c if n > next_n: a, b = next_n, n else: b,a = next_n, n P2[(a,b)] = c f(next_n, n, c) c += 1 print(C) f(1, -1, 0) for ab in AB: print((P2[ab]))
p02850
'''catupper ''' import sys sys.setrecursionlimit(1000000)#DFSは再帰の上限回数に注意 n = int(eval(input())) edge = [[] for i in range(n)] a = [0] * n#頂点を格納しておく配列 b = [0] * n color_dict = {}#色を覚えておく k = 0 def dfs(x, last = -1, ban_color = -1): #lastは、どこから来たか、逆走を防ぐ。使っちゃいけない色も引数 global k#グローバル変数 color = 1 for to in edge[x]: if to == last:continue #来た頂点に戻ろうとしたら、何もしない if color == ban_color:color += 1 #使っちゃいけない色なら、新しい色にする color_dict[(x, to)] = color dfs(to, x, color) #次の頂点toについてDFS。来たのはxから。前の頂点で使った色はダメ。 color += 1#色を新しくする k = max(k, color-1)#何色を使ったか、覚えておく for i in range(n-1): a[i], b[i] = list(map(int, input().split())) a[i] -= 1#0-indexにする b[i] -= 1 edge[a[i]].append(b[i])#無向グラフ edge[b[i]].append(a[i]) dfs(0)#最初の頂点をDFSに入れてスタート print(k)#まず、何色必要かを出力 for i in range(n-1):#辺の色を1から頂点番号-1まで出力 if (a[i], b[i]) in color_dict:#辞書から答を出力 print((color_dict[(a[i], b[i])])) else: print((color_dict[(b[i], a[i])]))
'''catupper ポイントA.再帰DFSを使う。 ポイントB.入力に注意。 辺は頂点を結ぶので(a[i], b[i])で表現され、対応する色を color_dict[(a[i], b[i])]としている。 配列が二重配列になっているので、注意。 ポイントC.色を頂点の順番で辺毎に出力する。辺の数は頂点-1個。 for i in range(n-1): if (a[i], b[i]) in color_dict: ''' import sys sys.setrecursionlimit(1000000)#DFSは再帰の上限回数に注意 n = int(eval(input())) edge = [[] for i in range(n)] #どの頂点とどの頂点が繋がっているかを格納しておく配列 a = [0] * n#頂点aに繋がっている頂点bの番号を格納しておく配列 b = [0] * n color_dict = {}#色を覚えておく k = 0 def dfs(x, last = -1, ban_color = -1): #lastは、どこから来たか、逆走を防ぐ。使っちゃいけない色も引数 global k#グローバル変数 color = 1 for to in edge[x]: #配列edgeに格納されている次の頂点toを順番にチェック if to == last:continue #来た頂点に戻ろうとしたら、何もしない if color == ban_color:color += 1 #使っちゃいけない色なら、新しい色にする color_dict[(x, to)] = color dfs(to, x, color) #次の頂点toについてDFS。来たのはxから。前の頂点で使った色はダメ。 color += 1#色を新しくする k = max(k, color-1)#何色を使ったか、覚えておく for i in range(n-1): a[i], b[i] = list(map(int, input().split())) a[i] -= 1#0-indexにする b[i] -= 1 edge[a[i]].append(b[i])#無向グラフ edge[b[i]].append(a[i]) dfs(0)#最初の頂点をDFSに入れてスタート #print(color_dict) print(k)#まず、何色必要かを出力 for i in range(n-1):#辺の色を1から頂点番号-1まで出力 print((color_dict[(a[i], b[i])])) ''' if (a[i], b[i]) in color_dict:#辞書から答を出力 print(color_dict[(a[i], b[i])]) else: print(color_dict[(b[i], a[i])]) '''
p02850
#!/usr/bin/env pypy3 import itertools UNDEF = 0 def mex(s): for i in itertools.count(1): if i not in s: return i def color_edges(n, edges): adj_list = [set() for _ in range(n)] for i, (a, b) in enumerate(edges): adj_list[a].add(i) adj_list[b].add(i) colors = [UNDEF for _ in range(n - 1)] for v in range(n): adj_es = adj_list[v] num_adj = len(adj_es) cur_cols = set(colors[i] for i in adj_es if colors[i] != UNDEF) new_cols = set() while len(cur_cols) < num_adj: nc = mex(cur_cols) cur_cols.add(nc) new_cols.add(nc) for u in adj_es: if colors[u] == UNDEF: colors[u] = new_cols.pop() return max(colors), colors def main(): n = int(input()) edges = [] for _ in range(n - 1): a, b = (int(z) - 1 for z in input().split()) edges.append((a, b)) k, cs = color_edges(n, edges) print(k) print(*cs, sep="\n") if __name__ == "__main__": main()
#!/usr/bin/env pypy3 import itertools UNDEF = 0 def color_edges(n, edges): adj_list = [set() for _ in range(n)] for i, (a, b) in enumerate(edges): adj_list[a].add(i) adj_list[b].add(i) colors = [UNDEF] * (n - 1) for v in range(n): adj_es = adj_list[v] num_adj = len(adj_es) cur_cols = set(colors[i] for i in adj_es if colors[i] != UNDEF) new_cols = set() for i in itertools.count(1): if len(cur_cols) + len(new_cols) >= num_adj: break elif i not in cur_cols: new_cols.add(i) for u in adj_es: if colors[u] == UNDEF: colors[u] = new_cols.pop() return max(colors), colors def main(): n = int(input()) edges = [] for _ in range(n - 1): a, b = (int(z) - 1 for z in input().split()) edges.append((a, b)) k, cs = color_edges(n, edges) print(k) print(*cs, sep="\n") if __name__ == "__main__": main()
p02850
from collections import deque, OrderedDict n = int(input()) edges = [tuple(map(int, input().split())) for _ in range(n-1)] # print(edges) tree = [[] for _ in range(n)] # Zero-based index. グラフを陽に持つ。 edge_color = OrderedDict() # 辺のタプルをキーにした順序付き辞書 for e in edges: a = e[0] - 1 b = e[1] - 1 tree[a].append(b) tree[b].append(a) edge_color[(min(a, b), max(a, b))] = 0 print(max(len(v) for v in tree)) seen = [False] * n # 踏破 que = deque() que_append = que.append que_popleft = que.popleft start = 0 seen[start] = True que_append(start) # ある頂点に接する辺にすでに塗られた色のセット。 v_based_color = [set() for _ in range(n)] while len(que): v = que_popleft() color_i = 1 # One-based index. for adj in tree[v]: if seen[adj]: continue seen[adj] = True que_append(adj) while color_i in v_based_color[v]: # その頂点からの辺で使われていない色になるまで足す。 color_i += 1 edge_color[(min(v, adj), max(v, adj))] = color_i # 辺の両端の頂点が触れている色のセットに追加。 v_based_color[v].add(color_i) v_based_color[adj].add(color_i) color_i += 1 {print(c) for c in edge_color.values()}
from collections import OrderedDict, deque def main(): n = int(eval(input())) edges = [tuple(map(int, input().split())) for _ in range(n - 1)] tree = [[] for _ in range(n)] # こうしないとすべて同じリストObjになる. coloring = OrderedDict() for e in edges: a, b = e[0] - 1, e[1] - 1 tree[a].append(b) tree[b].append(a) coloring[(a, b)] = 0 q = deque() seen = [False] * n q.append(0) col_count_by_v = [set() for _ in range(n)] while len(q): new_v = q.popleft() seen[new_v] = True color_i = 1 # One-based index. for adj in tree[new_v]: if seen[adj]: continue q.append(adj) while color_i in col_count_by_v[new_v]: color_i += 1 coloring[(new_v, adj)] = color_i col_count_by_v[new_v].add(color_i) col_count_by_v[adj].add(color_i) color_i += 1 print((len(set(coloring.values())))) for c in list(coloring.values()): print(c) if __name__ == '__main__': main()
p02850
n=int(eval(input())) l=[[0 for i in range(n-1)]for j in range(n)] m=[0]*n t=[] w=[] for p in range(n-1): e = list(map(int, input().split())) w.append(e) for i in range(n-1): a=w[i][0]-1 b=w[i][1]-1 m[a] +=1 m[b] +=1 k=0 while True: if l[a][k]==0 and l[b][k]==0: l[a][k]=1 l[b][k]=1 break else: k +=1 t.append(k+1) c=max(m) print(c) for g in range(n-1): print((t[g]))
n=int(eval(input())) l=[[] for j in range(n)] m=[e for e in range(n-1)] t=[] for i in range(n-1): a, b = list(map(int, input().split())) a -=1 b -=1 buf = min(list(set(m)^set(l[a]+l[b]))) l[a].append(buf) l[b].append(buf) """ while True: if (k in l[a])==False and (k in l[b])==False: l[a].append(k) l[b].append(k) break else: k +=1 """ t.append(buf+1) print((max(t))) for g in range(n-1): print((t[g]))
p02850
from collections import defaultdict from collections import deque from collections import OrderedDict import itertools from sys import stdin input = stdin.readline def main(): N = int(input()) G = [[] for _ in range(N)] dic = {} for i in range(N-1): a, b = map(lambda x: int(x)-1, input().split()) G[a].append(b) G[b].append(a) dic[(a, b)] = i dic[(b, a)] = i color = [0]*(N-1) upcol = [0]*(N) upcol[0] = None visited = set() q = deque([0]) max_col = 0 while len(q): now = q.popleft() visited.add(now) c = 0 for next_ in G[now]: if next_ not in visited: c += 1 if upcol[now] is None or not(upcol[now] == c): color[dic[(now, next_)]] = c upcol[next_] = c else: c += 1 color[dic[(now, next_)]] = c upcol[next_] = c q.append(next_) max_col = max(max_col, c) print(max_col) print(*color, sep='\n') if(__name__ == '__main__'): main()
from collections import deque from sys import stdin input = stdin.readline def main(): N = int(input()) G = [[] for _ in range(N)] dic = {} for i in range(N-1): a, b = map(lambda x: int(x)-1, input().split()) G[a].append(b) G[b].append(a) dic[(a, b)] = i dic[(b, a)] = i color = [0]*(N-1) upcol = [0]*(N) upcol[0] = None visited = set() q = deque([0]) max_col = 0 while len(q): now = q.popleft() visited.add(now) c = 0 for next_ in G[now]: if next_ in visited: continue c += 1 if upcol[now] == c: c += 1 color[dic[(now, next_)]] = c upcol[next_] = c q.append(next_) max_col = max(max_col, c) print(max_col) print(*color, sep='\n') if(__name__ == '__main__'): main()
p02850
from collections import deque N = int(eval(input())) edges = [[] for i in range(N)] e_list = [] for i in range(N-1): a,b = list(map(int, input().split())) a -= 1 b -= 1 e_list.append((a,b)) edges[a].append((b,i)) edges[b].append((a,i)) ans = [0] * (N-1) """ bfs pattern """ q = deque() next_v = edges[0] for c, (u,i) in enumerate(next_v): q.append((u, i, c+1)) ans[i] = c+1 while q: u_p, _, c_p = q.popleft() next_v = edges[u_p] cnt = 1 for j, (u, i) in enumerate(next_v): # すでに彩色されている辺はダメ if ans[i] > 0: continue # 親と色がかぶったら+1 if cnt == c_p: cnt += 1 ans[i] = cnt q.append((u,i,cnt)) cnt += 1 print((max(ans))) for a in ans: print(a)
from collections import deque N = int(eval(input())) edges = [[] for i in range(N)] e_list = [] for i in range(N-1): a,b = list(map(int, input().split())) a -= 1 b -= 1 e_list.append((a,b)) edges[a].append((b,i)) edges[b].append((a,i)) ans = [0] * (N-1) """ bfs pattern """ q = deque() next_v = edges[0] for c, (u,i) in enumerate(next_v): q.append((u, i, c+1)) ans[i] = c+1 while q: u_p, _, c_p = q.popleft() next_v = edges[u_p] cnt = 1 for u, i in next_v: # すでに彩色されている辺はダメ if ans[i] > 0: continue # 親と色がかぶったら+1 if cnt == c_p: cnt += 1 ans[i] = cnt q.append((u,i,cnt)) cnt += 1 print((max(ans))) for a in ans: print(a)
p02850
import sys input = sys.stdin.readline sys.setrecursionlimit(50000) tree = {} edges = [] colors = set() N = 0 def readlines(n): for _ in range(n): a, b = list(map(int, input().split())) yield a, b def to_tree(edges_, n): tree_ = {i:[] for i in range(1,n+1)} for a, b in edges_: tree_[a].append(b) tree_[b].append(a) return tree_ def suc(u, parent): for v in tree[u]: if (u, v) != (u, parent): yield u, v def assign(assignment, u, parent): suc_edges = suc(u, parent) if not suc_edges: return lest_colors = colors - {assignment.get((parent, u))} for edge, color in zip(suc_edges, lest_colors): assignment[edge] = color v = edge[0] if edge[1] == u else edge[1] assign(assignment, v, u) def main(): global tree, edges, colors, N N = int(eval(input())) colors = set(range(1,N)) edges = list(readlines(N-1)) tree = to_tree(edges, N) ans = {} assign(ans, 1, None) print((max(ans.values()))) for edge in edges: print((ans[edge])) if __name__ == "__main__": main()
import sys input = sys.stdin.readline sys.setrecursionlimit(50000) tree = {} edges = [] colors = set() N = 0 def readlines(n): for _ in range(n): a, b = list(map(int, input().split())) yield a, b def to_tree(edges_, n): tree_ = {i:[] for i in range(1,n+1)} for a, b in edges_: tree_[a].append(b) tree_[b].append(a) return tree_ def suc(u, parent): for v in [v for v in tree[u] if (u,v) in edges and (u,v) != (u, parent)]: yield u, v def assign(assignment, u, parent): suc_edges = suc(u, parent) if not suc_edges: return lest_colors = colors - {assignment.get((parent, u))} for edge, color in zip(suc_edges, lest_colors): assignment[edge] = color v = edge[0] if edge[1] == u else edge[1] assign(assignment, v, u) def main(): global tree, edges, colors, N N = int(eval(input())) colors = set(range(1,N)) edges = list(readlines(N-1)) tree = to_tree(edges, N) ans = {} assign(ans, 1, None) print((max(ans.values()))) for edge in edges: print((ans[edge])) if __name__ == "__main__": main()
p02850
import sys input = sys.stdin.readline N = int(eval(input())) AB = [[int(i) for i in input().split()] for _ in range(N-1)] # graph[i]: 頂点iの親と子の集合 graph = [[] for _ in range(N+1)] for a,b in AB: graph[a].append(b) graph[b].append(a) # 根 root = 1 # parent[i]: 頂点iの親 parent = [0]*(N+1) # トポロジカル順序 order = [] # 未探索の頂点 stack = [root] # dfsでparentを求める while stack: # n: 探索する頂点 n = stack.pop() order.append(n) for j in graph[n]: # jがnの親の場合 if j == parent[n]: continue parent[j] = n stack.append(j) # color[i]: 頂点iと親を繋ぐ辺の色 color = [-1] * (N+1) # dfsで頂点iから出る辺の色を塗る for i in order: # 既に使用した色 ng = color[i] # 色 c = 1 for j in graph[i]: # jがiの親の場合(塗装済みなのでcontinue) if j == parent[i]: continue if c == ng: c += 1 # 頂点iと頂点jの辺に色を塗る color[j] = c c += 1 # 入力順に辺の色を出力する answer = [color[a] if parent[a]==b else color[b] for a,b in AB] print((max(answer))) print(("\n".join(map(str,answer))))
import sys input = sys.stdin.readline N = int(eval(input())) AB = [[int(i) for i in input().split()] for _ in range(N-1)] # graph[i]: 頂点iの親と子の集合 graph = [[] for _ in range(N+1)] for a,b in AB: graph[a].append(b) graph[b].append(a) # 根 root = 1 # parent[i]: 頂点iの親 parent = [0]*(N+1) # トポロジカル順序(dfsの順番) order = [] # 未探索の頂点 stack = [root] # dfsでparentを求める while stack: # n: 探索する頂点 n = stack.pop() order.append(n) for j in graph[n]: # jがnの親の場合 if j == parent[n]: continue parent[j] = n stack.append(j) # color[i]: 頂点iと親を繋ぐ辺の色 color = [-1] * (N+1) # dfsで頂点iから出る辺の色を塗る for i in order: # 既に使用した色 ng = color[i] # 色 c = 1 for j in graph[i]: # jがiの親の場合(塗装済みなのでcontinue) if j == parent[i]: continue if c == ng: c += 1 # 頂点iと頂点jの辺に色を塗る color[j] = c c += 1 # 入力順に辺の色を出力する answer = [color[a] if parent[a]==b else color[b] for a,b in AB] print((max(answer))) print(("\n".join(map(str,answer))))
p02850
# input n = int(eval(input())) edge = [[0, 0, 0] for i in range(n-1)] for i in range(n-1): edge[i][0] ,edge[i][1] = list(map(int, list(input().split()))) # process k = 0 pcolors = [0 for i in range(n)] for i in range(n): color = 0 for j in range(n-1): if edge[j][0] == i+1: color += 1 if color == pcolors[i]: color += 1 edge[j][2] = color pcolors[edge[j][1]-1] = color if k < color: k = color # output print(k) for e in edge: print((e[2]))
import sys sys.setrecursionlimit(10**7) # input n = int(eval(input())) edges = [[] for i in range(n)] for i in range(n-1): a ,b = list(map(int, list(input().split()))) edges[a-1].append((b-1, i)) # process ans = [0]*(n-1) def f(a, c): color = 1 for b, i in edges[a]: if color == c: color += 1 ans[i] = color f(b, color) color += 1 f(0, 0) # output print((max(ans))) for i in ans: print(i)
p02850
import sys sys.setrecursionlimit(10 ** 6) # input = sys.stdin.readline #### int1 = lambda x: int(x) - 1 def II(): return int(eval(input())) def MI(): return list(map(int, input().split())) def MI1(): return list(map(int1, input().split())) def LI(): return list(map(int, input().split())) def LI1(): return list(map(int1, input().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def printlist(lst, k='\n'): print((k.join(list(map(str, lst))))) INF = float('inf') from collections import deque def solve(): N = II() E = [[] for _ in range(N)] out = [] for i in range(N-1): a, b = MI1() E[a].append(b) E[b].append(a) out.append((a, b)) q = deque([(0, -1, -1)]) memo = {} max_color = 0 while len(q) > 0: current, v_pre, c_pre = q.popleft() color = 1 for nv in E[current]: if nv == v_pre: continue if color == c_pre: color += 1 q.append((nv, current, color)) memo[(min(nv, current), max(nv, current))] = color max_color = max(max_color, color) color += 1 # print(memo) print(max_color) for t in out: print((memo[t])) if __name__ == '__main__': solve()
import sys sys.setrecursionlimit(10 ** 6) # input = sys.stdin.readline #### int1 = lambda x: int(x) - 1 def II(): return int(eval(input())) def MI(): return list(map(int, input().split())) def MI1(): return list(map(int1, input().split())) def LI(): return list(map(int, input().split())) def LI1(): return list(map(int1, input().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def printlist(lst, k='\n'): print((k.join(list(map(str, lst))))) INF = float('inf') from collections import deque def solve(): N = II() E = [[] for _ in range(N)] for i in range(N-1): a, b = MI1() E[a].append((b, i)) E[b].append((a, i)) q = deque([(0, -1, -1)]) ans = [0] * (N-1) while len(q) > 0: current, v_pre, c_pre = q.popleft() color = 1 for (nv, idx) in E[current]: if nv == v_pre: continue if color == c_pre: color += 1 q.append((nv, current, color)) ans[idx] = color color += 1 print((max(ans))) printlist(ans) if __name__ == '__main__': solve()
p02850
n=int(eval(input())) g = [[]for i in range(n)] ab = [list(map(int,input().split()))for i in range(n-1)] for i in range(n-1): g[ab[i][0]-1].append(ab[i][1]-1) ans = [[-1 for i in range(n)]for j in range(n)] banColor = [-1]*n from queue import deque q = deque([]) q.append(0) ma = 0 while q: nord = q.popleft() offset = 0 for idx,value in enumerate(g[nord]): if idx ==banColor[nord]: offset += 1 ans[nord][value] = idx + offset banColor[value] = idx+offset q.append(value) ma = max(ma,idx+offset+1) print(ma) for i in range(n-1): print((ans[ab[i][0]-1][ab[i][1]-1]+1))
from queue import deque n=int(eval(input())) ab = [list(map(int,input().split()))for i in range(n-1)] g = [[]for i in range(n)] for i,j in ab: g[i-1].append(j-1) ans = {} banColor = [-1]*n q = deque([]) q.append(0) ma = 0 while q: nord = q.popleft() offset = 0 for idx,value in enumerate(g[nord]): if idx ==banColor[nord]: offset += 1 ans[(nord,value)]= idx + offset banColor[value] = idx+offset q.append(value) ma = max(ma,idx+offset+1) print(ma) for i,j in ab: print((ans[(i-1,j-1)]+1))
p02850
from collections import deque n=int(eval(input())) E=[[]for _ in range(n)] L=[] for i in range(n-1): a,b=list(map(int,input().split())) E[a-1].append(b-1) L.append(b-1) que=deque([0]) ans=[0]*n while que: s=que.pop() color=1 for ni in E[s]: if color==ans[s]: color+=1 ans[ni]=color color+=1 que.append(ni) print((max(ans))) for ni in L: print((ans[ni]))
from collections import deque n=int(eval(input())) E=[[]for _ in range(n)] L=[] for i in range(n-1): a,b=list(map(int,input().split())) E[a-1].append(b-1) L.append(b-1) que=deque([0]) ans=[0]*n while que: s=que.popleft() color=1 for ni in E[s]: if color==ans[s]: color+=1 ans[ni]=color color+=1 que.append(ni) print((max(ans))) for ni in L: print((ans[ni]))
p02850
from collections import deque n=int(eval(input())) E=[[]for _ in range(n)] L=[] for i in range(n-1): a,b=list(map(int,input().split())) E[a-1].append(b-1) L.append(b-1) que=deque([0]) ans=[0]*n while que: s=que.popleft() color=1 for ni in E[s]: if color==ans[s]: color+=1 ans[ni]=color color+=1 que.append(ni) print((max(ans))) for ni in L: print((ans[ni]))
from collections import deque n=int(eval(input())) E=[[]for _ in range(n)] L=[] for i in range(n-1): a,b=list(map(int,input().split())) E[a-1].append(b-1) L.append(b-1) que=deque([0]) ans=[0]*n while que: s=que.pop() color=1 for ni in E[s]: if color==ans[s]: color+=1 ans[ni]=color color+=1 que.append(ni) print((max(ans))) for i in L: print((ans[i]))
p02850
#!/usr/bin/env python3 import sys import collections as cl def II(): return int(sys.stdin.readline()) def MI(): return list(map(int, sys.stdin.readline().split())) def LI(): return list(map(int, sys.stdin.readline().split())) def main(): N = II() graph = [[] for i in range(N)] prev = [-1 for i in range(N)] colors = {} edges = [] for _ in range(N-1): a, b = MI() graph[a-1].append(b-1) graph[b-1].append(a-1) edges.append([a-1, b-1]) max_edge = 0 max_edge_idx = -1 for i in range(len(graph)): length = len(graph[i]) if length >= max_edge: max_edge = length max_edge_idx = i deque = cl.deque([max_edge_idx]) unused_colors_tmp = set(list(range(1, max_edge+1))) while len(deque) > 0: target = deque.popleft() pre = prev[target] unused_colors = set(unused_colors_tmp) pre_key = (target, pre) if target < pre else (pre, target) if pre != -1: unused_colors.remove(colors[pre_key]) connecteds = graph[target] color = 1 for connected in connecteds: key = (target, connected) if target < connected else ( connected, target) if key in colors: unused_colors.discard(colors[key]) continue while not color in unused_colors: color += 1 colors[key] = color prev[connected] = target deque.append(connected) unused_colors.remove(color) print(max_edge) for edge in edges: print((colors[(edge[0], edge[1])])) main()
#!/usr/bin/env python3 import sys import collections as cl def II(): return int(sys.stdin.readline()) def MI(): return list(map(int, sys.stdin.readline().split())) def LI(): return list(map(int, sys.stdin.readline().split())) def main(): N = II() graph = [[] for i in range(N)] prev = [-1 for i in range(N)] colors = {} edges = [] for _ in range(N-1): a, b = MI() graph[a-1].append(b-1) graph[b-1].append(a-1) edges.append([a-1, b-1]) max_edge = 0 max_edge_idx = -1 for i in range(len(graph)): length = len(graph[i]) if length >= max_edge: max_edge = length max_edge_idx = i deque = cl.deque([max_edge_idx]) while len(deque) > 0: target = deque.popleft() pre = prev[target] pre_key = (target, pre) if target < pre else (pre, target) used_color = 0 if pre != -1: used_color = colors[pre_key] connecteds = graph[target] color = 1 for connected in connecteds: key = (target, connected) if target < connected else ( connected, target) if key in colors: continue if color == used_color: color += 1 colors[key] = color prev[connected] = target deque.append(connected) color += 1 print(max_edge) for edge in edges: print((colors[(edge[0], edge[1])])) main()
p02850
N = int(eval(input())) V = [[] for _ in range(N)] E = [[-1 for _ in range(N)] for _ in range(N)] yobidasi = [] for i in range(N - 1): a, b = list(map(int, input().split())) V[a - 1].append(b - 1) V[b - 1].append(a - 1) yobidasi.append([a - 1, b - 1]) color_num = 0 for i in range(N): color_num = max(color_num, len(V[i])) visited = [False for _ in range(N)] Q = [[0, 0]] print(color_num) while Q: cur, parent_color = Q.pop(0) visited[cur] = True color_lst = [n for n in range(1, color_num + 1)] if parent_color != 0: color_lst.pop(parent_color - 1) for adj in V[cur]: if visited[adj] == False: # print("paint") color = color_lst.pop(0) E[min(adj, cur)][max(adj, cur)] = color Q.append([adj, color]) for i in range(N - 1): print((E[yobidasi[i][0]][yobidasi[i][1]]))
N = int(eval(input())) V = [[] for _ in range(N)] E = dict() yobidasi = [] for i in range(N - 1): a, b = list(map(int, input().split())) V[a - 1].append(b - 1) V[b - 1].append(a - 1) yobidasi.append([a - 1, b - 1]) E[a - 1, b - 1] = -1 color_num = 0 for i in range(N): color_num = max(color_num, len(V[i])) visited = [False for _ in range(N)] Q = [[0, 0]] print(color_num) while Q: cur, parent_color = Q.pop(0) visited[cur] = True color_lst = [n for n in range(1, color_num + 1)] if parent_color != 0: color_lst.pop(parent_color - 1) for adj in V[cur]: if visited[adj] == False: visited[adj] = True color = color_lst.pop(0) E[min(adj, cur), max(adj, cur)] = color Q.append([adj, color]) for i in range(N - 1): print((E[yobidasi[i][0], yobidasi[i][1]]))
p02850
# -*- coding: utf-8 -*- import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(eval(input())) def MAP(): return list(map(int, input().split())) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') sys.setrecursionlimit(10 ** 9) INF = 10 ** 18 MOD = 10 ** 9 + 7 N = INT() nodes = [[] for i in range(N)] edges = {} for i in range(N-1): a, b = MAP() a -= 1; b -= 1 nodes[a].append(b) nodes[b].append(a) edges[(a, b)] = [i, -1] mx = 0 used = [set() for i in range(N)] ans = [0] * (N-1) cnt = 0 for u in range(N): mx = max(mx, len(nodes[u])) for v in nodes[u]: a, b = min(u, v), max(u, v) if edges[(a, b)][1] == -1: color = 1 while color in used[a] or color in used[b]: color += 1 edges[(a, b)][1] = color used[a].add(color) used[b].add(color) i = edges[(a, b)][0] ans[i] = str(color) cnt += 1 if cnt == N-1: break else: continue break print(mx) print(('\n'.join(ans)))
# -*- coding: utf-8 -*- import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(eval(input())) def MAP(): return list(map(int, input().split())) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') sys.setrecursionlimit(10 ** 9) INF = 10 ** 18 MOD = 10 ** 9 + 7 N = INT() nodes = [[] for i in range(N)] edges = {} for i in range(N-1): a, b = MAP() a -= 1; b -= 1 nodes[a].append(b) nodes[b].append(a) edges[(a, b)] = [i, -1] mx = 0 used = [set() for i in range(N)] ans = [0] * (N-1) cnt = 0 for u in range(N): mx = max(mx, len(nodes[u])) color = 1 for v in nodes[u]: a, b = min(u, v), max(u, v) if edges[(a, b)][1] == -1: while color in used[a] or color in used[b]: color += 1 edges[(a, b)][1] = color used[a].add(color) used[b].add(color) i = edges[(a, b)][0] ans[i] = str(color) color += 1 cnt += 1 if cnt == N-1: break else: continue break print(mx) print(('\n'.join(ans)))
p02850
n = int(eval(input())) g = [[] for x in range(n+1)] s = [] for _ in range(n-1): a,b = [int(x) for x in input().split()] g[a].append(b) g[b].append(a) s.append([a,b]) from collections import deque color = [[-1]*(n+1) for x in range(n+1)] index = [] q = deque() q.append([1,0]) ans = 0 while q: num = 0 p = q.popleft() for i in g[p[0]]: if color[p[0]][i]==-1: num += 1 if p[1]==num: num += 1 color[p[0]][i] = num color[i][p[0]] = num q.append([i,num]) ans = max(ans,num) print(ans) for a,b in s: print((color[a][b]))
n = int(eval(input())) g = [[] for _ in range(n)] z = [] for _ in range(n-1): a,b = [int(x)-1 for x in input().split()] g[a].append(b) g[b].append(a) if a<b: z.append((a,b)) else: z.append((b,a)) from collections import deque parent = [0]*n mc = 0 en = dict() q = deque() used = [0]*n q.append(0) used[0] = 1 while q: p = q.popleft() color = 0 for i in g[p]: if used[i] != 1: color += 1 used[i] = 1 if color==parent[p]: color += 1 if p<i: en[(p,i)]=color else: en[(i,p)]=color parent[i] = color q.append(i) mc = max(mc,color) print(mc) for i in z: print((en[i]))
p02850
from collections import deque def readinput(): n=int(eval(input())) nList=[] for _ in range(n+1): nList.append([]) edges=[] for _ in range(n-1): a,b=list(map(int,input().split())) edges.append((a,b)) nList[a].append(b) nList[b].append(a) return n,nList,edges def bfs(s,nList): #print(nList) WHITE=0 GRAY=1 BLACK=2 status=[WHITE]*(n+1) parent=[0]*(n+1) color=[] maxcolor=0 for i in range(n+1): color.append([0]*(n+1)) Q=deque([]) Q.append(s) while(len(Q)>0): u=Q.popleft() usedcolor=set() usedcolor.add(color[u][parent[u]]) for t in nList[u]: if status[t]==WHITE: status[t]=GRAY parent[t]=u for col in range(1,n): if col in usedcolor: continue color[u][t]=col color[t][u]=col usedcolor.add(col) maxcolor=max(maxcolor,col) break Q.append(t) status[u]=BLACK #print(u,usedcolor) return color, maxcolor def main(n,nList,edges): color, maxcolor=bfs(1,nList) print(maxcolor) for a,b in edges: print((color[a][b])) if __name__=='__main__': n,nList,edges=readinput() main(n,nList,edges)
from collections import deque def readinput(): n=int(eval(input())) nList=[] for _ in range(n+1): nList.append([]) edges=[] for _ in range(n-1): a,b=list(map(int,input().split())) edges.append((a,b)) nList[a].append(b) nList[b].append(a) return n,nList,edges def bfs(s,nList): #print(nList) WHITE=0 GRAY=1 BLACK=2 status=[WHITE]*(n+1) parent=[0]*(n+1) color=[] maxcolor=0 for i in range(n+1): color.append([0]*(n+1)) Q=deque([]) Q.append(s) while(len(Q)>0): u=Q.popleft() usedcolor=color[u][parent[u]] col=1 for t in nList[u]: if status[t]==WHITE: status[t]=GRAY parent[t]=u if col==usedcolor: col+=1 color[u][t]=col color[t][u]=col maxcolor=max(maxcolor,col) Q.append(t) col+=1 status[u]=BLACK #print(u,usedcolor) return color, maxcolor def main(n,nList,edges): color, maxcolor=bfs(1,nList) print(maxcolor) for a,b in edges: print((color[a][b])) if __name__=='__main__': n,nList,edges=readinput() main(n,nList,edges)
p02850
from collections import deque def readinput(): n=int(eval(input())) nList=[] for _ in range(n+1): nList.append([]) edges=[] for _ in range(n-1): a,b=list(map(int,input().split())) edges.append((a,b)) nList[a].append(b) nList[b].append(a) return n,nList,edges def bfs(s,nList): #print(nList) WHITE=0 GRAY=1 BLACK=2 status=[WHITE]*(n+1) parent=[0]*(n+1) color=[] maxcolor=0 for i in range(n+1): color.append([0]*(n+1)) Q=deque([]) Q.append(s) while(len(Q)>0): u=Q.popleft() usedcolor=color[u][parent[u]] col=1 for t in nList[u]: if status[t]==WHITE: status[t]=GRAY parent[t]=u if col==usedcolor: col+=1 color[u][t]=col color[t][u]=col maxcolor=max(maxcolor,col) Q.append(t) col+=1 status[u]=BLACK #print(u,usedcolor) return color, maxcolor def main(n,nList,edges): color, maxcolor=bfs(1,nList) print(maxcolor) for a,b in edges: print((color[a][b])) if __name__=='__main__': n,nList,edges=readinput() main(n,nList,edges)
from collections import deque def readinput(): n=int(eval(input())) nList=[] for _ in range(n+1): nList.append([]) edges=[] for _ in range(n-1): a,b=list(map(int,input().split())) edges.append((a,b)) nList[a].append(b) #nList[b].append(a) return n,nList,edges def bfs(s,nList): #print(nList) WHITE=0 GRAY=1 BLACK=2 status=[WHITE]*(n+1) parent=[0]*(n+1) color=[0]*(n+1) maxcolor=0 Q=deque([]) Q.append(s) while(len(Q)>0): u=Q.popleft() usedcolor=color[u] col=1 for t in nList[u]: if status[t]==WHITE: status[t]=GRAY parent[t]=u if col==usedcolor: col+=1 color[t]=col Q.append(t) col+=1 maxcolor=max(maxcolor,col-1) status[u]=BLACK #print(u,usedcolor) return color, maxcolor def main(n,nList,edges): color, maxcolor=bfs(1,nList) print(maxcolor) for a,b in edges: print((color[b])) if __name__=='__main__': n,nList,edges=readinput() main(n,nList,edges)
p02850
import sys input = sys.stdin.buffer.readline N=int(eval(input())) val=[list(map(int, input().split())) for i in range(N-1)] arr=[set() for i in range(N)] col=[set() for i in range(N)] colarr=[0]*(N-1) alen=[0]*N coldict={} for i in range(N-1): a=val[i][0]-1 b=val[i][1]-1 arr[a].add(b) arr[b].add(a) coldict[(a,b)]=i colmax=0 flag=0 for i in range(N): alen[i]=len(arr[i]) if len(arr[i])>colmax: colmax=len(arr[i]) flag=i colall=set(range(1,colmax+1)) coltemp=set(colall) arrtemp=set(arr[flag]) for f in arrtemp: p=coltemp.pop() if flag<f: colarr[coldict[(flag,f)]]=p else: colarr[coldict[(f,flag)]]=p col[f].add(p) arr[f].remove(flag) que=[set() for i in range(N)] que[0]=que[0] | arr[flag] for i in range(N-1): for t in que[i]: arrtemp=arr[t] if len(arrtemp)>0: C=set(range(1,alen[t]+1)) coltemp=C^(C&col[t]) que[i+1]=que[i+1] | arrtemp for f in arrtemp: p=coltemp.pop() col[f].add(p) arr[f].remove(t) if t<f: colarr[coldict[(t,f)]]=p else: colarr[coldict[(f,t)]]=p print(colmax) for i in range(N-1): print((colarr[i]))
import sys input = sys.stdin.buffer.readline N=int(eval(input())) val=[list(map(int, input().split())) for i in range(N-1)] arr=[set() for i in range(N)] col=[set() for i in range(N)] colarr=[0]*(N-1) coldict={} for i in range(N-1): a=val[i][0]-1 b=val[i][1]-1 arr[a].add(b) arr[b].add(a) coldict[(a,b)]=i colmax=0 flag=0 for i in range(N): if len(arr[i])>colmax: colmax=len(arr[i]) flag=i colall=set(range(1,colmax+1)) coltemp=1 arrtemp=set(arr[flag]) for f in arrtemp: p=coltemp coltemp+=1 if flag<f: colarr[coldict[(flag,f)]]=p else: colarr[coldict[(f,flag)]]=p col[f].add(p) arr[f].remove(flag) que=[set() for i in range(N)] que[0]=que[0] | arr[flag] for i in range(N-1): for t in que[i]: arrtemp=arr[t] if len(arrtemp)>0: coltemp=1 que[i+1] |= arrtemp for f in arrtemp: while(1): if coltemp not in col[t]: break coltemp+=1 p=coltemp coltemp+=1 col[f].add(p) arr[f].remove(t) if t<f: colarr[coldict[(t,f)]]=p else: colarr[coldict[(f,t)]]=p print(colmax) for i in range(N-1): print((colarr[i]))
p02850
from collections import deque n = int(eval(input())) tree = [[] for _ in range(n)] edge = [] color = [set() for _ in range(n)] ans = dict() for i in range(n-1): a,b = list(map(int,input().split())) edge.append([a,b]) tree[a-1].append(b) tree[b-1].append(a) work_q = deque([]) visited = set() work_q.append(1) visited.add(1) while work_q: here = work_q.popleft() for i in tree[here-1]: col = 1 if i not in visited: work_q.append(i) visited.add(i) while col in color[here-1]: col += 1 color[here-1].add(col) color[i-1].add(col) ans[(here-1,i-1)] = col col += 1 print((max(ans.values()))) for i in range(n-1): print((ans[edge[i][0]-1,edge[i][1]-1]))
import sys from collections import deque input = sys.stdin.readline sys.setrecursionlimit(10 ** 9) n = int(input()) edge = [[] for _ in range(n+1)] for i in range(n-1): a, b = map(int,input().split()) edge[a].append((b, i)) edge[b].append((a, i)) colors = 0 for i, line in enumerate(edge): colors = max(colors, len(line)) print(colors) work_q = deque() work_q.append((1, -1, -1)) color = [-1] * (n - 1) while work_q: here, prev, col = work_q.popleft() cnt = 1 for to, ind in edge[here]: if to == prev: continue if cnt == col: cnt += 1 color[ind] = cnt work_q.append((to, here, cnt)) cnt += 1 print(*color, sep="\n")
p02850
import sys sr = lambda: sys.stdin.readline().rstrip() ir = lambda: int(sr()) lr = lambda: list(map(int, sr().split())) N = ir() AB = [lr() for _ in range(N-1)] # 0-indexed edges = [[] for _ in range(N+1)] # 1-indexed for a, b in AB: edges[a].append(b) edges[b].append(a) order = [] # 頂点1を根とした時、上からの頂点の順番 parent = [0] * (N+1) # 1-indexed stack = [1] while stack: x = stack.pop() order.append(x) for y in edges[x]: if parent[x] == y: continue parent[y] = x stack.append(y) color = [-1] * (N+1) # 1-indexed 頂点iの親方向への辺の色 for o in order: ng = color[o] c = 1 for z in edges[o]: if z == parent[o]: continue if c == ng: c += 1 color[z] = c c += 1 answer = [] for i in range(N-1): a, b = AB[i] if a == parent[b]: answer.append(color[b]) else: answer.append(color[a]) print((max(answer))) print(('\n'.join(map(str, answer)))) # 12
import sys sr = lambda: sys.stdin.readline().rstrip() ir = lambda: int(sr()) lr = lambda: list(map(int, sr().split())) N = ir() AB = [lr() for _ in range(N-1)] # 0-indexed edges = [[] for _ in range(N+1)] # 1-indexed for a, b in AB: edges[a].append(b) edges[b].append(a) order = [] # 頂点1を根とした時、上からの頂点の順番 parent = [0] * (N+1) # 1-indexed stack = [1] while stack: x = stack.pop() order.append(x) for y in edges[x]: if parent[x] == y: continue parent[y] = x stack.append(y) color = [-1] * (N+1) # 1-indexed 頂点iの親方向への辺の色 for o in order: ng = color[o] c = 1 for z in edges[o]: if z == parent[o]: continue if c == ng: c += 1 color[z] = c c += 1 answer = [] append = answer.append for i in range(N-1): a, b = AB[i] if a == parent[b]: append(color[b]) else: append(color[a]) print((max(answer))) print(('\n'.join(map(str, answer)))) # 12
p02850
import sys from collections import defaultdict sr = lambda: sys.stdin.readline().rstrip() ir = lambda: int(sr()) lr = lambda: list(map(int, sr().split())) N = ir() AB = [lr() for _ in range(N-1)] graph = [[] for _ in range(N+1)] # 1-indexed for i in range(N-1): a, b = AB[i] AB[i] = tuple(sorted([a, b])) graph[a].append(b) graph[b].append(a) AB_to_C = defaultdict(int) root = 1 parent = [0] * (N+1) stack = [root] while stack: cur = stack.pop() used = 0 if parent[cur] != 0: used = AB_to_C[tuple(sorted([cur, parent[cur]]))] color = 1 for next in graph[cur]: if next == parent[cur]: continue parent[next] = cur while True: if color == used: color += 1 else: AB_to_C[tuple(sorted([cur, next]))] = color color += 1 break stack.append(next) answer = [0] * (N-1) for i in range(N-1): answer[i] = AB_to_C[AB[i]] print(max(answer)) print(*answer, sep='\n')
import sys sr = lambda: sys.stdin.readline().rstrip() ir = lambda: int(sr()) lr = lambda: list(map(int, sr().split())) N = ir() graph = [[] for _ in range(N+1)] AB = [lr() for _ in range(N-1)] for a, b in AB: graph[a].append(b) graph[b].append(a) root = 1 parent = [0] * (N+1) order = [] stack = [(root, 0)] color = [0] * (N+1) # 頂点と、親方向の辺を対応させる while stack: cur, ng = stack.pop() c = 1 for next in graph[cur]: if next == parent[cur]: continue if c == ng: c += 1 parent[next] = cur color[next] = c stack.append((next, c)) c += 1 answer = [] append = answer.append for a, b in AB: if parent[a] == b: append(color[a]) else: append(color[b]) print(max(answer)) print(*answer, sep='\n') # 02
p02850
from functools import reduce from operator import mul N = int(eval(input())) ab = [tuple(map(int, input().split())) for _ in range(N-1)] E_n = {k: 0 for k in ab} for i in range(1,N+1): items = {k:v for k,v in list(E_n.items()) if i in k} c = 1 if items == {}: continue elif reduce(mul, list(items.values())) != 0: continue for k in list(items.keys()): if items[k] != 0: continue while True: if c not in list(items.values()): items[k] = c break else: c += 1 E_n.update(items) #if reduce(mul, E_n.values()) != 0: break print((len(set(E_n.values())))) for k in ab: print((E_n[k]))
N = int(input()) edge = {} tree = [[] for i in range(N)] colors = [1]*(N-1) c_p = [[] for i in range(N)] for i in range(N-1): a,b = map(int,input().split()) a,b = a-1,b-1 tree[a].append(b) edge[(a,b)] = i for i in range(N): c = 1 for v_c in tree[i]: while c in c_p[i]: c+=1 colors[edge[(i,v_c)]] = c c_p[v_c].append(c) c+=1 print(max(colors)) print(*colors, sep="\n")
p02850
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement from collections import deque,defaultdict,Counter from bisect import bisect_left,bisect_right from operator import itemgetter from heapq import heapify,heappop,heappush from queue import Queue,LifoQueue,PriorityQueue from copy import deepcopy from time import time from functools import reduce import string import sys sys.setrecursionlimit(10 ** 7) def input() : return sys.stdin.readline().strip() def INT() : return int(eval(input())) def MAP() : return list(map(int,input().split())) def LIST() : return list(MAP()) def bfs(k): c = [[0]*n for i in range(n)] dist = [-1]*n que = deque([0]) dist[0] = 0 v_prev = 0 while que: v = que.popleft() d = dist[v] color = set(range(1, k+1)) used = [] for w in g[v]: if dist[w] > -1: used.append(c[v][w]) color.difference_update(used) color = deque(color) for w in g[v]: if dist[w] > -1: continue c[v][w] = c[w][v] = color.popleft() dist[w] = d + 1 que.append(w) return c n = INT() a = [0]*(n-1) b = [0]*(n-1) g = [[] for i in range(n)] for i in range(n-1): a[i], b[i] = MAP() a[i] -= 1 b[i] -= 1 g[a[i]].append(b[i]) g[b[i]].append(a[i]) k = 0 for x in g: k = max(k, len(x)) print(k) c = bfs(k) for i in range(n-1): print((c[a[i]][b[i]]))
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement from collections import deque,defaultdict,Counter from bisect import bisect_left,bisect_right from operator import itemgetter from heapq import heapify,heappop,heappush from queue import Queue,LifoQueue,PriorityQueue from copy import deepcopy from time import time from functools import reduce import string import sys sys.setrecursionlimit(10 ** 7) def input() : return sys.stdin.readline().strip() def INT() : return int(eval(input())) def MAP() : return list(map(int,input().split())) def MAP1() : return [int(x)-1 for x in input().split()] def LIST() : return list(MAP()) def solve(): n = INT() Q = [tuple(MAP1()) for _ in range(n-1)] deg = [0]*n adj = [[] for _ in range(n)] color = dict() for a, b in Q: deg[a] += 1 deg[b] += 1 adj[a].append(b) adj[b].append(a) def dfs(s, p): nouse = -1 if p > -1: nouse = color[(min(s,p),max(s,p))] c = 1 for t in adj[s]: if t == p: continue if c == nouse: c += 1 color[(min(s,t),max(s,t))] = c dfs(t,s) c += 1 dfs(1,-1) print((max(deg))) for a, b in Q: print((color[(a, b)])) if __name__ == '__main__': solve()
p02850
from collections import deque def main(): N, *AB = list(map(int, open(0).read().split())) E = [[] for _ in range(N + 1)] memo = {} for i, (a, b) in enumerate(zip(*[iter(AB)] * 2)): E[a].append(b) E[b].append(a) memo[(a, b)] = i memo[(b, a)] = i K = max(len(e) for e in E) A = [""] * (N - 1) cand = {i for i in range(1, K + 1)} visited = [False] * (N + 1) Q = deque([(-1, 1)]) visited[1] = True while Q: c, v = Q.popleft() C = cand - {c} for u in E[v]: if visited[u]: continue visited[u] = True c = C.pop() Q.append((c, u)) A[memo[(v, u)]] = str(c) print(K) print(("\n".join(A))) main()
from collections import deque def main(): N, *AB = list(map(int, open(0).read().split())) E = [set() for _ in range(N + 1)] memo = {} for i, (a, b) in enumerate(zip(*[iter(AB)] * 2)): E[a].add(b) E[b].add(a) memo[(a, b)] = i memo[(b, a)] = i K = max(len(e) for e in E) A = [""] * (N - 1) visited = [False] * (N + 1) Q = deque([(-1, 1)]) visited[1] = True while Q: a, v = Q.popleft() c = 0 for u in E[v]: E[u].remove(v) c += 1 if c == a: c += 1 Q.append((c, u)) A[memo[(v, u)]] = str(c) E[v] = set() print(K) print(("\n".join(A))) main()
p02850
from collections import deque N, *AB = list(map(int, open(0).read().split())) E = [[] for _ in range(N + 1)] memo = {} for i, (a, b) in enumerate(zip(*[iter(AB)] * 2)): E[a].append(b) E[b].append(a) memo[(a, b)] = i memo[(b, a)] = i K = max(len(e) for e in E) A = [0] * (N - 1) cand = {i for i in range(1, K + 1)} visited = [False] * (N + 1) Q = deque([(-1, 1)]) visited[1] = True while Q: p, v = Q.popleft() c = 0 for u in E[v]: if visited[u]: continue visited[u] = True c += 1 + (c + 1 == p) Q.append((c, u)) A[memo[(v, u)]] = c print(K) for a in A: print(a)
from collections import deque def main(): N, *AB = list(map(int, open(0).read().split())) E = [[] for _ in range(N + 1)] I = [] for a, b in zip(*[iter(AB)] * 2): E[a].append(b) I.append(b) Q = deque([1]) C = [0] * (N + 1) while Q: v = Q.popleft() c = 0 for u in E[v]: c += 1 + (c + 1 == C[v]) C[u] = c Q.append(u) print((max(C))) for i in I: print((C[i])) main()
p02850
from collections import deque def main(): N, *AB = list(map(int, open(0).read().split())) E = [[] for _ in range(N + 1)] I = [] for a, b in zip(*[iter(AB)] * 2): E[a].append(b) I.append(b) Q = deque([1]) C = [0] * (N + 1) while Q: v = Q.popleft() c = 0 for u in E[v]: c += 1 + (c + 1 == C[v]) C[u] = c Q.append(u) print((max(C))) for i in I: print((C[i])) main()
from collections import deque def main(): N, *AB = list(map(int, open(0).read().split())) E = [[] for _ in range(N + 1)] B = AB[1::2] for a, b in zip(*[iter(AB)] * 2): E[a].append(b) Q = deque([1]) C = [0] * (N + 1) while Q: v = Q.popleft() c = 0 for u in E[v]: c += 1 + (c + 1 == C[v]) C[u] = c Q.append(u) print((max(C))) for b in B: print((C[b])) main()
p02850
from collections import deque def main(): N, *AB = list(map(int, open(0).read().split())) A, B = AB[::2], AB[1::2] E = [[] for _ in range(N + 1)] for a, b in zip(A, B): E[a].append(b) Q = deque([1]) C = [0] * (N + 1) while Q: v = Q.popleft() c = 0 for u in E[v]: c += 1 + (c + 1 == C[v]) C[u] = c Q.append(u) print((max(C))) for b in B: print((C[b])) main()
""" challenge case in: 3 1 3 2 3 out: 1 1 1 """ from collections import deque def main(): N, *AB = list(map(int, open(0).read().split())) B = AB[1::2] E = [[] for _ in range(N + 1)] for a, b in zip(*[iter(AB)] * 2): E[a] += b, Q = deque([1]) C = [0] * (N + 1) while Q: v = Q.popleft() c = 0 for u in E[v]: c += 1 + (c + 1 == C[v]) C[u] = c Q += u, print((max(C))) for b in B: print((C[b])) main()
p02850
""" challenge case in: 3 1 3 2 3 out: 1 1 1 """ from collections import deque def main(): N, *AB = list(map(int, open(0).read().split())) B = AB[1::2] E = [[] for _ in range(N + 1)] for a, b in zip(*[iter(AB)] * 2): E[a] += b, Q = deque([1]) C = [0] * (N + 1) while Q: v = Q.popleft() c = 0 for u in E[v]: c += 1 + (c + 1 == C[v]) C[u] = c Q += u, print((max(C))) for b in B: print((C[b])) main()
""" challenge case in: 3 1 3 2 3 out: 1 1 1 """ from collections import deque def main(): N, *AB = list(map(int, open(0).read().split())) B = AB[1::2] E = [[] for _ in range(N + 1)] for a, b in zip(*[iter(AB)] * 2): E[a].append(b) Q = deque([1]) C = [0] * (N + 1) while Q: v = Q.popleft() c = 0 for u in E[v]: c += 1 + (c + 1 == C[v]) C[u] = c Q.append(u) print((max(C))) for b in B: print((C[b])) main()
p02850
from collections import defaultdict, deque, Counter N = int(eval(input())) edges = {} counter = Counter() nodes = defaultdict(set) K = 0 for i in range(N - 1): u, v = list(map(int, input().split(' '))) counter[u] += 1 counter[v] += 1 K = max(K, counter[u], counter[v]) nodes[u].add(v) nodes[v].add(u) edges[(u, v)] = i colors = set([1 + k for k in range(K)]) checked = set() queue = deque([(1, 0)]) edge_colors = [0] * N while queue: u, uc = queue.popleft() checked.add(u) if len(checked) == N: break for v, vc in zip(nodes[u] - checked, colors - {uc}): edge_colors[edges[(min(u, v), max(u, v))]] = vc queue.append((v, vc)) print(K) for i in range(N - 1): print((edge_colors[i]))
from collections import defaultdict, deque, Counter N = int(eval(input())) counter = Counter() nodes = defaultdict(list) edges = [] for i in range(N - 1): u, v = list(map(int, input().split(' '))) nodes[u].append((v, i)) nodes[v].append((u, i)) edges.append((u, v)) K = 0 for node in list(nodes.values()): K = max(K, len(node)) checked = set() queue = deque([(1, 0)]) edge_colors = [0] * N while queue: u, uc = queue.popleft() checked.add(u) color = 1 for v, e in nodes[u]: if v in checked: continue if color == uc: color += 1 edge_colors[e] = color queue.append((v, color)) color += 1 print(K) for i in range(N - 1): print((edge_colors[i]))
p02850
import sys from collections import deque input = sys.stdin.readline N = int(eval(input())) G = [[] for _ in range(N)] ans = {} queue = deque([]) e = [] for l in range(N-1): temp = list(map(int,input().split())) temp[0] -= 1 temp[1] -= 1 e.append(tuple(temp)) ans[(temp[0],temp[1])] = 0 ans[(temp[1],temp[0])] = 0 G[temp[0]].append(temp[1]) G[temp[1]].append(temp[0]) if l == 0: queue.append(temp[0]) #使えない色 nuc = [[0] for _ in range(N)] #使った色 auc = [] #答え def bfs(x): k = 1 for i in G[x]: if ans[(x,i)] ==0: queue.append(i) flag = 1 while flag: if k not in nuc[x]: ans[(x,i)] = k ans[(i,x)] = k nuc[x].append(k) nuc[i].append(k) if k not in auc: auc.append(k) flag = 0 else: k += 1 while len(queue) > 0: next_ = queue.popleft() bfs(next_) print((len(auc))) for m in e: print((ans[m]))
def main(): import sys from collections import deque input = sys.stdin.readline N = int(eval(input())) G = [[] for _ in range(N)] ans = {} queue = deque([]) e = [] for l in range(N-1): temp = list(map(int,input().split())) temp[0] -= 1 temp[1] -= 1 e.append(tuple(temp)) ans[(temp[0],temp[1])] = 0 ans[(temp[1],temp[0])] = 0 G[temp[0]].append(temp[1]) G[temp[1]].append(temp[0]) if l == 0: queue.append(temp[0]) #使えない色 nuc = [[0] for _ in range(N)] #使った色 auc = [] #答え def bfs(x): k = 1 for i in G[x]: if ans[(x,i)] ==0: queue.append(i) flag = 1 while flag: if k not in nuc[x]: ans[(x,i)] = k ans[(i,x)] = k nuc[x].append(k) nuc[i].append(k) if k not in auc: auc.append(k) flag = 0 else: k += 1 while len(queue) > 0: next_ = queue.popleft() bfs(next_) print((len(auc))) for m in e: print((ans[m])) if __name__ == '__main__': main()
p02850
import sys def input(): return sys.stdin.readline()[:-1] import math from itertools import permutations, combinations from collections import deque sys.setrecursionlimit(10**7) N = int(eval(input())) ab = [] edges = [[] for _ in range(N)] for i in range(N-1): a, b = list(map(int, input().split())) edges[a-1].append(b-1) edges[b-1].append(a-1) ab.append((a, b)) K = max(list(map(len, edges))) print(K) adjm = [[0]*N for _ in range(N)] Q = deque() for edge in edges[0]: Q.append((0, edge)) while Q: labels = set(i for i in range(1, K+1)) points = Q.popleft() p0, p1 = points set1 = set(adjm[p0]) can_use_labels = labels - (set1) use_label = can_use_labels.pop() adjm[p0][p1] = use_label adjm[p1][p0] = use_label for p in edges[p1]: if adjm[p1][p] == 0: Q.append((p1, p)) for abi in ab: a, b = abi[0], abi[1] print((adjm[a-1][b-1]))
import sys def input(): return sys.stdin.readline()[:-1] import math from itertools import permutations, combinations from collections import deque sys.setrecursionlimit(10**7) N = int(eval(input())) ab = [list(map(int, input().split())) for _ in range(N-1)] edges = [[] for _ in range(N)] for abi in ab: a, b = abi[0], abi[1] edges[a-1].append(b-1) edges[b-1].append(a-1) K = max(list(map(len, edges))) print(K) adjm = [[0]*N for _ in range(N)] Q = deque() for edge in edges[0]: Q.append((0, edge)) while Q: labels = set(i for i in range(1, K+1)) points = Q.popleft() p0, p1 = points set1 = set(adjm[p0]) can_use_labels = labels - set1 use_label = can_use_labels.pop() adjm[p0][p1] = use_label adjm[p1][p0] = use_label for p in edges[p1]: if p != p0: Q.append((p1, p)) for abi in ab: a, b = abi[0], abi[1] print((adjm[a-1][b-1]))
p02850
from collections import deque def color_available(unavailable, K): idx = 0 L = len(unavailable) unavailable = sorted(unavailable) for color in range(K): if idx < L and color == unavailable[idx]: idx += 1 else: yield color def bfs(graph, N, K, start): colors = [dict() for _ in range(N)] visited = [0] * N visited[start] = 1 que = deque([start]) while que: node = que.popleft() gen = color_available(list(colors[node].values()), K) color = 1 for n in graph[node]: if not visited[n]: visited[n] = 1 color = next(gen) colors[node][n] = color colors[n][node] = color que.append(n) return colors N = int(eval(input())) graph = [[] for _ in range(N)] inputs = tuple(tuple([int(n) - 1 for n in input().split()]) for _ in range(N - 1)) counts = [0] * N for i, j in inputs: graph[i].append(j) graph[j].append(i) counts[i] += 1 counts[j] += 1 K = max(counts) colors = bfs(graph, N, K, 0) print(K) for i, j in inputs: print((colors[i][j] + 1))
from collections import deque def color_available(unavailable, K): idx = 0 L = len(unavailable) unavailable = sorted(unavailable) for color in range(K): if idx < L and color == unavailable[idx]: idx += 1 else: yield color def bfs(graph, N, K, start): colors = [dict() for _ in range(N)] visited = [0] * N visited[start] = 1 que = deque([start]) while que: node = que.popleft() gen = color_available(list(colors[node].values()), K) for n in graph[node]: if not visited[n]: visited[n] = 1 colors[node][n] = colors[n][node] = next(gen) que.append(n) return colors N = int(eval(input())) graph = [[] for _ in range(N)] inputs = tuple(tuple([int(n) - 1 for n in input().split()]) for _ in range(N - 1)) counts = [0] * N for i, j in inputs: graph[i].append(j) graph[j].append(i) counts[i] += 1 counts[j] += 1 K = max(counts) colors = bfs(graph, N, K, 0) print(K) for i, j in inputs: print((colors[i][j] + 1))
p02850
from collections import deque def main(): N = int(eval(input())) # 辺の集合を隣接リストとして入力 E = [[] for i in range(N+1)] edge_order = [] for i in range(N-1): a,b = list(map(int, input().split())) E[a].append(b) edge_order.append(b) # 頂点1から幅優先探索 queue = deque([1]) color = [0] * (N+1) while queue: V = queue.popleft() c = 1 for i in E[V]: if c == color[V]: c += 1 color[i] = c c += 1 queue.append(i) print((max(color))) for i in edge_order: print((color[i])) if __name__ == "__main__": main()
import sys from collections import deque read = sys.stdin.read def main(): N, *ab = list(map(int, read().split())) E = [[] for _ in range(N + 1)] edge_order = [] for a, b in zip(*[iter(ab)] * 2): E[a].append(b) edge_order.append(b) # 頂点1から幅優先探索 queue = deque([1]) color = [0] * (N+1) while queue: V = queue.popleft() c = 1 for i in E[V]: if c == color[V]: c += 1 color[i] = c c += 1 queue.append(i) print((max(color))) for i in edge_order: print((color[i])) if __name__ == "__main__": main()
p02850
from collections import deque N = int(eval(input())) G = {i:[] for i in range(1,N+1)} E = {} A = [] for _ in range(N-1): a,b = list(map(int,input().split())) A.append((a,b)) G[a].append(b) G[b].append(a) E[(a,b)] = 0 hist = [0 for _ in range(N+1)] heap = deque([1]) c = 1 for y in G[1]: E[(1,y)]=c c += 1 K = c-1 hist[1]=1 while heap: x = heap.popleft() for y in G[x]: if hist[y]==0: K = max(K,len(G[y])) col = [0 for _ in range(K+1)] for z in G[y]: if y<z: col[E[(y,z)]]=1 else: col[E[(z,y)]]=1 cur = 1 for z in G[y]: if y<z and E[(y,z)]==0: for i in range(cur,K+1): if col[i]==0: E[(y,z)]=i col[i]=1 cur = i+1 break elif z<y and E[(z,y)]==0: for i in range(cur,K+1): if col[i]==0: E[(z,y)]=i col[i]=1 cur = i+1 break heap.append(y) hist[y]=1 print(K) for e in A: print((E[e]))
from collections import deque N = int(eval(input())) G = {i:[] for i in range(1,N+1)} E = {} A = [] for _ in range(N-1): a,b = list(map(int,input().split())) A.append((a,b)) G[a].append(b) G[b].append(a) E[(a,b)] = 0 hist = [0 for _ in range(N+1)] heap = deque([1]) c = 1 for y in G[1]: E[(1,y)]=c c += 1 K = c-1 hist[1]=1 while heap: x = heap.popleft() for y in G[x]: if hist[y]==0: K = max(K,len(G[y])) col = [0 for _ in range(min(K,len(G[y]))+1)] for z in G[y]: if y<z and E[(y,z)]<len(col): col[E[(y,z)]]=1 elif z<y and E[(z,y)]<len(col): col[E[(z,y)]]=1 cur = 1 for z in G[y]: if y<z and E[(y,z)]==0: for i in range(cur,K+1): if col[i]==0: E[(y,z)]=i cur = i+1 break elif z<y and E[(z,y)]==0: for i in range(cur,K+1): if col[i]==0: E[(z,y)]=i cur = i+1 break heap.append(y) hist[y]=1 print(K) for e in A: print((E[e]))
p02850
from collections import Counter,defaultdict,deque from heapq import heappop,heappush,heapify import sys,bisect,math,itertools,fractions,pprint sys.setrecursionlimit(10**8) mod = 10**9+7 mod2 = 998244353 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) def inpln(n): return list(int(sys.stdin.readline()) for i in range(n)) n = inp() aa = [0] * (n-1) bb = [0] * (n-1) g = [[] for i in range(n)] res = defaultdict(lambda : defaultdict(int)) for i in range(n-1): a,b = inpl() aa[i] = a-1 bb[i] = b-1 g[a-1].append(b-1) g[b-1].append(a-1) def dfs(i,c=-1,p=-1): # print('i:{}'.format(i)) cnt = 1 for j in g[i]: # print(res[j][i]) if j == p: continue if cnt == c: cnt += 1 res[i][j] = cnt res[j][i] = cnt cnt += 1 dfs(j,res[i][j],i) dfs(0) m = 0 for i in g: m = max(m, len(i)) print(m) for i in range(n-1): print((res[aa[i]][bb[i]]))
from collections import Counter,defaultdict,deque from heapq import heappop,heappush,heapify import sys,bisect,math,itertools,fractions,pprint sys.setrecursionlimit(10**8) mod = 10**9+7 mod2 = 998244353 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) def inpln(n): return list(int(sys.stdin.readline()) for i in range(n)) n = inp() g = [[] for i in range(n)] edges = [] res = [defaultdict(int) for i in range(n)] for i in range(n-1): a,b = inpl() a -= 1 b -= 1 g[a].append(b) g[b].append(a) edges.append([a,b]) def dfs(e,prev_edge=-1,prev_color=-1): cnt = 1 for ne in g[e]: if res[e][ne] or ne == prev_edge: continue if cnt == prev_color: cnt += 1 res[e][ne] = cnt res[ne][e] = cnt dfs(ne,e,cnt) cnt += 1 dfs(0) m = 0 for eee in g: m = max(m, len(eee)) print(m) for a,b in edges: print((res[a][b]))
p02850
import queue N = int(eval(input())) tree = [[]for _ in range(N+1)] for i in range(1,N): a,b = list(map(int,input().split())) tree[a].append( [b,i]) tree[b].append([a,i]) que = queue.Queue() node = [-1]*(N+1) edge = [-1]*N que.put(1) node[1] = 1 maxi = max([len(i) for i in tree]) color = [[i for i in range(1,maxi+1)] for _ in range(N+1)] while(True): if que.empty(): break start = que.get() for i in tree[start]: if edge[i[1]] == -1: col = max(color[i[0]][0],color[start][0]) edge[i[1]] = col que.put(i[0]) color[i[0]].remove(col) color[start].remove(col) print(maxi) for i in edge[1:]: print(i)
import queue N = int(eval(input())) tree = [[]for _ in range(N+1)] for i in range(1,N): a,b = list(map(int,input().split())) tree[a].append( [b,i]) tree[b].append([a,i]) que = queue.Queue() node = [-1]*(N+1) edge = [-1]*N que.put(1) node[1] = 1 maxi = 1 color = [[] for _ in range(N+1)] while(True): if que.empty(): break start = que.get() for i in tree[start]: col = 1 if edge[i[1]] == -1: que.put(i[0]) while(True): if col in (color[i[0]] + color[start]): col +=1 if col > maxi: maxi = col else : break edge[i[1]] = col color[i[0]].append(col) color[start].append(col) print(maxi) for i in edge[1:]: print(i)
p02850