Problem:


Score : 400 points

Problem Statement

Given is a tree G with N vertices.
The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i.

Consider painting the edges in G with some number of colors.
We want to paint them so that, for each vertex, the colors of the edges incident to that vertex are all different.

Among the colorings satisfying the condition above, construct one that uses the minimum number of colors.

Constraints

 2 \le N \le 10^5

 1 \le a_i \lt b_i \le N

All values in input are integers.

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}

Output

Print N lines.

The first line should contain K, the number of colors used.

The (i+1)-th line (1 \le i \le N-1) should contain c_i, the integer representing the color of the i-th edge, where 1 \le c_i \le K must hold.

If there are multiple colorings with the minimum number of colors that satisfy the condition, printing any of them will be accepted.

Sample Input 1

3
1 2
2 3

Sample Output 1

2
1
2

Sample Input 2

8
1 2
2 3
2 4
2 5
4 7
5 6
6 8

Sample Output 2

4
1
2
3
4
1
1
2

Sample Input 3

6
1 2
1 3
1 4
1 5
1 6

Sample Output 3

5
1
2
3
4
5



Sample input:
3
1 2
2 3


Sample output:
2
1
2

Submission status: Wrong Answer

Solution code:
class Edge:
	def __init__(s, t, i):
		self.index = s
		self.e_index = i

N = int(input())

ve = [{'index': i, 'edges': []} for i in range(N)]
e = [0 for i in range(N - 1)]

for i in range(N - 1):
	s, g = [int(x) - 1 for x in input().split()]
	
	ve[s]['edges'].append(i)
	ve[g]['edges'].append(i)
	
ve.sort(key=lambda x: len(x['edges']))
ve.reverse()

max = len(ve[0]['edges'])
for i in range(N):
	ed = ve[i]['edges']
	c = 1
	k = 0
	
	has_color = []
	for k in range(len(ed)):
		if e[ed[k]] != 0:
			has_color.append(e[ed[k]])
	
	c = 1
	k = 0
	while k < len(ed):
		if e[ed[k]] != 0:
			k += 1
			continue
		
		try:
			has_color.index(c)
			c += 1
			continue
		except:
			pass
		
		e[ed[k]] = c
		c += 1
		k += 1

c = 1
	
es = [str(x) for x in e]
print(max)
print("\n".join(es))

Submission status: Wrong Answer

Solution code:
from operator import mul
from functools import reduce
# from collections import Counter
# from itertools import combinations as comb
# from itertools import permutations as perm
# from copy import copy
# 配列二分法アルゴリズム
# https://docs.python.jp/3/library/bisect.html
# import bisect
# 桁数指定
# print('{:.3f}'.format(X))
# from collections import defaultdict
# dic = defaultdict(lambda: ...)
# 値で辞書をソート
# sorted(dic.items(), key=lambda x:x[1])
# ヒープキュー
# https://docs.python.org/ja/3/library/heapq.html
# import heapq
# 正規表現(regular expression)のためのモジュール
# import re

import sys

sys.setrecursionlimit(10**6)


def inpl():
    return list(map(int, input().split()))


# 重複組み合わせは nHr = (n + r - 1)Cn
def cmb(n, r):
    # combination
    if n < r:
        return 0
    r = min(n - r, r)
    if r == 0:
        return 1
    over = reduce(mul, range(n, n - r, -1))
    under = reduce(mul, range(1, r + 1))
    return over // under


def gcd(a, b):
    # greatest common divisor
    while b > 0:
        a, b = b, a % b

    return a


def lcm(a, b):
    # least common multiple
    return a * b // gcd(a, b)


def dfs(visit, a, v_b, v_color):
    visit[a] = True

    t_list = [t for t in tmp_list[a] if t != v_b]
    t_color = [c for c in range(ans) if v_color != c]
    # print(t_list, t_color)
    flag = True
    i = 0
    for i, b in enumerate(tmp_list[a]):
        if b == v_b:
            continue
        # print(a, b, c)
        # color[a][c] = True
        # color[b][c] = True
        if i >= v_color:
            i += 1
        c = i
        ans_c[min(a, b), max(a, b)] = c
        dfs(visit, b, a, c)
        i += 1

    return


N = int(input())
AB = [inpl() for i in range(N - 1)]

ans_c = {}
tmp_list = [[] for i in range(N + 1)]
for a, b in AB:
    tmp_list[a].append(b)
    tmp_list[b].append(a)

ans = max(len(a) for a in tmp_list)
# print(ans, "ans")
# color = [[False for j in range(ans)] for i in range(N + 1)]
visit = [False for i in range(N + 1)]
dfs(visit, 1, -1, -1)

print(ans)
for a, b in AB:
    print(ans_c[a, b] + 1)

Submission status: Wrong Answer

Solution code:
from collections import deque

N=int(input())
deg=[0 for v in range(N+1)];deg[0]=None
out=[set() for v in range(N+1)];deg[0]=None
for e in range(1,N):
    a,b=map(int,input().split())
    out[a].add((b,e));out[b].add((a,e))
for v in range(N+1):
    deg[v]=len(out[v])
# print(out) #DB
# print(deg) #DB

K=max(deg[1:])
# print(K) #DB

ecol=[0 for e in range(N+1)];ecol[0]=None

r=[False for v in range(N+1)];r[0]=None

q=deque()
q.append(1);r[1]=True
col=1 #色
while q:
    u=q.popleft() # 今いる頂点
    for vs in out[u]: # 今いる頂点の隣にある頂点と，その頂点に行くための辺の番号
        if not r[vs[0]]: # その頂点にまだ辿り着いていなければ
            ecol[vs[1]]=col # 辺をその色で塗り      
            r[vs[0]]=True # その頂点にたどり着いたこととし
            q.append(vs[0]) # その頂点をキューに加え
            col=1 if col==K else col+1 # 色を変える。

print(K)
for ecoli in ecol[1:]:
    print(K if ecoli==0 else ecoli)

Submission status: Wrong Answer

Solution code:
from collections import Counter
from itertools import chain
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(100000)


class Solver(object):
    def __init__(self):
        pass

    def solve(self, n: int, links: list):
        # flatten the links
        flatten_links = list(chain.from_iterable(links))
        max_count = Counter(flatten_links).most_common()[0][1]
        print(max_count)
        n_colors = [set() for _ in range(n)]
        ans = list()
        for link in links:
            if len(link) == 2:
                for c in range(1, max_count+1):
                    if c not in n_colors[link[0] - 1]:
                        if c not in n_colors[link[1] - 1]:
                            print(c)
                            n_colors[link[0] - 1].add(c)
                            n_colors[link[1] - 1].add(c)
                            break


def main():
    N = int(input())
    t_l = [[int(i) for i in input().split()] for _ in range(N)]

    solver = Solver()
    solver.solve(N, t_l)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
P = []
p, q = 0, 0
graph = [0] * n
graph2 = [0] * n
r = 0
for i in range(n-1):
    if i >= 1:
        p, q = a, b
    a, b = map(int,input().split())
        
    graph[a-1] += 1
    graph[b-1] += 1
    if q == a:
        P.append(max(graph[a-1], graph[b-1]) + 1)
    else:
        P.append(max(graph[a-1], graph[b-1]))

print(max(P))
for i in range(n-1):
    print(P[i])

Submission status: Wrong Answer

Solution code:
class Edge:
	def __init__(s, t, i):
		self.index = s
		self.e_index = i

N = int(input())

ve = [{'index': i, 'edges': []} for i in range(N)]
e = [0 for i in range(N)]

for i in range(N - 1):
	s, g = [int(x) - 1 for x in input().split()]
	
	ve[s]['edges'].append(i)
	ve[g]['edges'].append(i)
	
ve.sort(key=lambda x: len(x['edges']))
ve.reverse()

max = len(ve[0]['edges'])
for i in range(N):
	ed = ve[i]['edges']
	c = 1
	k = 0
	
	has_color = []
	for k in range(len(ed)):
		if e[ed[k]] != 0:
			has_color.append(e[ed[k]])
	
	c = 1
	k = 0
	while k < len(ed):
		if e[ed[k]] != 0:
			k += 1
			continue
		
		try:
			has_color.index(c)
			c += 1
			continue
		except:
			pass
		
		e[ed[k]] = c
		c += 1
		k += 1

c = 1
for i in range(len(e)):
	if e[i] == 0:
		e[i] = c
		c += 1
		c = c % max
	
es = [str(x) for x in e]
print("\n".join(es))

Submission status: Wrong Answer

Solution code:
import copy

N = int(input())

lst = [[] for _ in range(N + 1)]
ans = []

for _ in range(N - 1):
  a, b = (int(i) for i in input().split(' '))
  
  lsttmp = [i for i in range(N)]
  lsttmp = lsttmp[1:]
  lsttmp = list(set(lsttmp) - set(lst[a]))
  lsttmp = list(set(lsttmp) - set(lst[b]))
  
  cnt = lsttmp[0]
  
  ans.append(cnt)
  lst[a].append(cnt)
  lst[b].append(cnt)

ans.insert(0, max(ans))

for i in ans:
  print(str(i))

Submission status: Wrong Answer

Solution code:
n=int(input())
AB=sorted([list(map(int,input().split())) for i in range(n-1)])
tree={}
for a,b in AB:
    if a not in tree:
        tree[a]=[b]
    else:
        tree[a] +=[b]
ans=[0]*(n+1)
cnt=0
for i in tree.keys():
    line=[i+1 for i in range(len(tree[i]))]
    flag=0
    for j,k in enumerate(tree[i]):
        if line[j]==ans[i]:flag=1
        if flag:
            ans[k]=line[j]+1
            continue
        ans[k]=line[j]
print(max(ans))
for i in range(2,n+1):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
n = int(input())
edge = []
v_edge = [0]*n

for i in range(n-1):
    ai,bi = map(int,input().split())
    edge.append([ai,bi])
    v_edge[ai-1] += 1
    v_edge[bi-1] += 1
    
k = max(v_edge)
print(k)

c_edge = [set([]) for i in range(n)]

for i in range(len(edge)):
    ai,bi = edge[i]
    for ci in range(1,k+1):
        if ci not in c_edge[ai-1]:
            c = ci
            break
    
    c_edge[ai-1].add(c)
    c_edge[bi-1].add(c)
    print(c)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys

def solve(N: int, a: "List[int]", b: "List[int]"):
    h = [set() for _ in range(N+1)]

    for i in range(N-1):
        h[a[i]].add(i)
        h[b[i]].add(i)

    max_color = 0
    for hh in h:
        max_color = max(len(hh),max_color)
    color = list(range(1,max_color+1))

    # colorList[i]が辺iのいろ
    colorList = [0]*(N-1)

    h.sort(key=lambda x: -len(x))
    for i in range(0,N):
        color_index = 0

        if len(h[i]) == 1 and colorList[list(h[i])[0]] > 0:
            continue

        cur = [colorList[b] for b in h[i] if colorList[b]>0] ##塗ってある色リスト
        
        if len(h[i]) == len(cur) and len(set(cur)) == len(cur):
            continue


        for hh in h[i]:
            if i == 0:
                colorList[hh] = color[color_index]
                color_index+=1
            if colorList[hh] > 0: ##塗って会ったらもういい
                continue
            else:            
                while color[color_index] in cur:
                    if color_index < max_color-1:
                        color_index+=1
                    else:
                        color_index = 0

                colorList[hh] = color[color_index]

    print(max_color)
    for c in colorList:
        print(c)

    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    a = [int()] * (N - 1)  # type: "List[int]"
    b = [int()] * (N - 1)  # type: "List[int]"
    for i in range(N - 1):
        a[i] = int(next(tokens))
        b[i] = int(next(tokens))
    solve(N, a, b)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
"""Coloring Edges on Tree
https://atcoder.jp/contests/abc146/tasks/abc146_d
"""
import sys
input = sys.stdin.readline


class Node:
    def __init__(self, num):
        self.num = num
        self.edge_colors = []


N = int(input())

# treeの初期化
tree = []
tree.append(Node(0))
for i in range(1, N + 1):
    tree.append(Node(i))


colors = []

ans = []
for i in range(N - 1):
    a, b = map(int, input().split())

    # edgeの１本目
    if len(colors) == 0:
        edge_color = 1
        colors.append(edge_color)
        tree[a].edge_colors.append(edge_color)
        tree[b].edge_colors.append(edge_color)
    else:
        used_colors = tree[a].edge_colors + tree[b].edge_colors
        # if len(used_colors) == 0:
        #     # その視点、終点の頂点に初めて辺が入る時
        #     edge_color = colors[0]
        #     tree[a].edge_colors.append(edge_color)
        #     tree[b].edge_colors.append(edge_color)
        # else:
        unused_colors = list(set(colors) - set(used_colors))
        if len(unused_colors) == 0:
            # 新しい色の辺を使う
            edge_color = len(colors) + 1
            colors.append(edge_color)
            tree[a].edge_colors.append(edge_color)
            tree[b].edge_colors.append(edge_color)
        else:
            # 元々あった色の辺を使う
            edge_color = unused_colors.pop()
            tree[a].edge_colors.append(edge_color)
            tree[b].edge_colors.append(edge_color)

    ans.append(edge_color)

print(len(colors))
for a in ans:
    print(a)

Submission status: Wrong Answer

Solution code:
N = int(input())
num = [[]for _ in range(N)]
for i in (range(N-1)):
  a, b = map(int, input().split())
  num[a].append(b)
answer = [0] * (N-1)
color = [-1] * (N)
max_num = 0
count = 0
for i in range(len(num)):
  if max_num <= len(num[i]):
    if i == 1:
      max_num = len(num[i])
    else:
      max_num = len(num[i]) + 1
  c = 1
  for j in range(len(num[i])):
    if c == color[i-1]:
      c += 1
    answer[count] = c
    color[num[i][j]-1] = c
    c += 1
    count += 1
print(max_num)
for i in answer:
  print(i)

Submission status: Wrong Answer

Solution code:
import collections

n = int(input())
edge = []
node = [0] * n
edge_color = collections.defaultdict(list)
for _ in range(n-1):
    edge.append(list(map(int, input().split())))

color = 1
ans = []
added_color = [1]
for e in edge:
    if node[e[0]-1] == 0 and node[e[1]-1] == 0:
        ans.append(color)
        edge_color[e[0]-1].append(color)
        edge_color[e[1]-1].append(color)
    else:
        r1 = set(added_color)-set(edge_color[e[0]-1])
        r2 = set(added_color)-set(edge_color[e[1]-1])
        r3 = list(r1 & r2)
        if len(r3) > 0:
            r3 = r3[0]
            ans.append(r3)
            flag = 1
            edge_color[e[0]-1].append(r3)
            edge_color[e[1]-1].append(r3)
        else:
            color += 1
            ans.append(color)
            added_color.append(color)
            edge_color[e[0]-1].append(color)
            edge_color[e[1]-1].append(color)
    node[e[0]-1] += 1
    node[e[1]-1] += 1

print(max(ans))
for a in ans:
    print(a)

Submission status: Wrong Answer

Solution code:
def sol():
    n=int(input())
    x=[set([]) for i in range(n+1)]
    ans=[]
    for i in range(n-1):
        a,b=map(int,input().split())
        c=x[a]|x[b]
        for j in range(1,n+1):
            if j not in c:
                ans.append(j)
                x[a].add(j)
                x[b].add(j)
                break
    #print(x)
    print(max(ans))
    for i in ans:
        print(i)

if __name__=="__main__":
    sol()

Submission status: Wrong Answer

Solution code:
from collections import deque

n = int(input())

g = {i: dict() for i in range(n)}

a_list = [0] * (n - 1)
b_list = [0] * (n - 1)
for i in range(n - 1):
    a, b = map(int, input().split())
    a_list[i] = a - 1
    b_list[i] = b - 1
    g[a - 1][b - 1] = -1
    g[b - 1][a - 1] = -1

k = max([len(g[a]) for a in range(n)])

used_color = [-1] * n
# BFS
queue = deque([0])
while len(queue) > 0:
    p = queue.popleft()
    c = used_color[p]
    for q in g[p].keys():
        if used_color[q] != -1:
            continue
        c += 1
        c %= k
        g[p][q] = c
        g[q][p] = c
        used_color[q] = c
        queue.append(q)

print(k)
for i in range(n - 1):
    print(g[a_list[i]][b_list[i]] + 1)

Submission status: Wrong Answer

Solution code:
N = int(input())
G = [list(map(int, input().split())) for _ in range(N-1)]

chk = [set() for _ in range(N)]
cnt = 1
ans = [0] * (N-1)
colors = set([1])

for i in range(N-1):
    tmpset = colors - chk[G[i][0]-1] - chk[G[i][1]-1]
    if tmpset == set():
        color = cnt + 1
        colors.add(color)
        cnt = color
    else:
        color = min(tmpset)
    chk[G[i][0]-1].add(color)
    chk[G[i][1]-1].add(color)
    ans[i] = color

print(cnt)
for i in range(len(ans)):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
N = int(input())
tree=[0 for _ in range(N)]
nodes=[]
for _ in range(N-1):
    m = list(map(int, input().split()))
    tree[m[0]-1]+=1
    tree[m[1]-1]+=1
    nodes.append(m)
print(max(tree))
colors = set([i+1 for i in range(max(tree))])
tree_col = [set() for _ in range(N)]
for i in nodes:
    if tree[i[0]-1]>tree[i[1]-1]:
        c = (colors-(tree_col[i[0]-1])).pop()
        tree_col[i[0]-1].add(c)
        tree_col[i[1]-1].add(c)
        print(c)
    else:
        c = (colors-(tree_col[i[1]-1])).pop()
        tree_col[i[0]-1].add(c)
        tree_col[i[1]-1].add(c)
        print(c)

Submission status: Wrong Answer

Solution code:
N = int(input())
edges = [list(map(int, input().split())) for _ in range(N-1)]

used = [set() for i in range(N+1)]
answer = []

for a, b in edges:
    cur = 1
    s = used[a] | used[b]
    while cur in s:
        cur += 1
    answer.append(cur)
    used[a].add(cur)
    used[b].add(cur)

print(max(answer))
print(*answer, sep='\n')

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
 
n = int(input())
ab = [list(map(int, input().split())) for _ in range(n-1)]
 
graph = [[] for _ in range(n)]
 
for a, b in ab:
    graph[a-1].append((b-1, -1))
    graph[b-1].append((a-1, -1))
 
# print(graph)
k = 0
for i in graph:
    if k< len(i):
        k = len(i)

stack = [(0, -1)]
visited = [-1]*n
 
# k = 0
print(k)
while stack:
    node, color = stack.pop()
    visited[node] = 1
 
    # if k < len(graph[node]):
    #     k = len(graph[node])
    tmp = 1
    for i, (child, child_color) in enumerate(graph[node]):
        if visited[child] == 1:
            continue
        if tmp == color:
            tmp += 1
        graph[node][i] = (child, tmp)
        print(tmp)
        stack.append((child, tmp))
        tmp +=1
 
# print(k)
# for a, b in ab:
#    for node, color in graph[a-1]:
#        if node == b-1:
#            print(color)

Submission status: Wrong Answer

Solution code:
n = int(input())
c = [0 for i in range(n+1)] #何本枝が入っているか、でているか
ans = [0] * (n-1)
v = [[0 for i in range(n)] for i in range(n)]
inp = [[] for _ in range (n)]
for i in range(n-1):
    a, b = map(int, input().split())
    c[a] += 1
    c[b] += 1
    i = 1
    while i in inp[a-1]:
        i += 1
    inp[b-1].append(i)
print(max(c))
for i in range(n):
    for ans in inp[i]:
        print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
e = [list(map(int, input().split())) for _ in range(n-1)]
c = [0 for _ in range(n-1)]
e.sort()
cl = [set() for _ in range(n)]

for itr in range(n-1):
    i = e[itr][0]-1
    j = e[itr][1]-1
    cn = 1
    while(1):
        if cn in cl[i] or cn in cl[j]:
            cn+=1
        else:
            break
    c[itr] = cn
    cl[i].add(cn)
    cl[j].add(cn)

print(max(c))
for num in c:
    print(num)

Submission status: Wrong Answer

Solution code:
N=int(input())
info=[list(map(int, input().split())) for _ in range(N-1)]
lst=[[] for i in range(N+1)]
for (a, b) in info:
  lst[a].append(b)
  lst[b].append(a)
K=max(len(l) for l in lst)
color_map=[[False for _ in range(K+1)] for _ in range(N+1)]
color_list=[0 for i in range(N-1)]
for i in range(N-1):
  a, b=info[i]
  for j in range(1, K+1):
    if not color_map[a][j] and not color_map[b][j]:
      color_map[a][j]=True
      color_map[b][j]=True
      color_list[i]=j
      break
print(K)
for i in range(N-1):
  print(color_list[i])

Submission status: Wrong Answer

Solution code:
N = int(input())
HEN = []
COUNT = []
for i in range(N-1):
    tmp = [int(i) for i in input().split()]
    HEN.append(tmp)
    COUNT.append(tmp[0])
    COUNT.append(tmp[1])
    
MAX = 0
for i in range(1,N+1):
    tmp = COUNT.count(i) 
    if tmp > MAX:
        MAX = tmp
print(MAX)

Pool = []
Pool_part = []
for i in range(MAX):
    Pool_part.append(0)

for i in range(N):
    Pool.append(Pool_part)

for i in range(N-1):
    A = HEN[i]
    x = A[0]  
    y = A[1] 

    for j in range(MAX):
        if Pool[x-1][j] == 0 and Pool[y-1][j] == 0:
            print(j+1)
            X = Pool[x-1]
            X[j] = 1
            Pool[x-1] = X
            break

Submission status: Wrong Answer

Solution code:
n = int(input())
l = [list(map(int, input().split())) for i in range(n-1)]

#print(l)

col = [[] for i in range(n)]
#col[0].append(1)
#print(col)
result = []
m = 0
for i in range(n-1):
    for j in range(1, n):
        x = l[i][0]-1
        y = l[i][1]-1
        if not j in col[x] and not y in col[y]:
            if j > m:
                m = j
            col[x].append(j)
            col[y].append(j)
            result.append(j)
            break

#print(result)
print(m)
for item in result:
    print(item)

Submission status: Wrong Answer

Solution code:
n = int(input())
edge = []
v_edge = [0]*n

for i in range(n-1):
    ai,bi = map(int,input().split())
    edge.append([ai,bi])
    v_edge[ai-1] += 1
    v_edge[bi-1] += 1
    
k = max(v_edge)
print(k)

c_edge = [set([]) for i in range(n)]

for i in range(len(edge)):
    ai,bi = edge[i]
    for ci in range(1,k+1):
        if ci not in c_edge[ai-1]:
            c = ci
    
    c_edge[ai-1].add(c)
    c_edge[bi-1].add(c)
    print(c)

Submission status: Wrong Answer

Solution code:
class Edge:
    def __init__(s, t, i):
        self.index=s
        self.e_index=i
n=int(input())
ve=[{'index': i, 'edges': []} for i in range(n)]
e=[0 for i in range(n)]
for i in range(n-1):
    s, g=[int(x) - 1 for x in input().split()]
    ve[s]['edges'].append(i)
    ve[g]['edges'].append(i)
ve.sort(key=lambda x: len(x['edges']))
ve.reverse()
max=len(ve[0]['edges'])
for i in range(n):
    ed=ve[i]['edges']
    c=1
    k=0
    has_color=[]
    for k in range(len(ed)):
        if e[ed[k]]!=0:
            has_color.append(e[ed[k]])
    c=1
    k=0
    while k<len(ed):
        if e[ed[k]]!=0:
            k+=1
            continue
        try:
            has_color.index(c)
            c+=1
            continue
        except:
            pass
        e[ed[k]]=c
        c+=1
        k+=1
for i in range(len(e)):
    if e[i]==0:
        e[i]=1
es=[str(x) for x in e]
print("\n".join(es))

Submission status: Wrong Answer

Solution code:
from collections import deque

class Node:
    def __init__(self, val):
        self.val = val
        self.adj = []
        self.edges = []
        #self.pec = None
        self.pec = 0
    # def __init__(self):
    #     self.adj = []

n = int(input())
ab = []
nodes = [None] * n

cntMap = {}

def addCount(v1, v2):
    if v1 not in cntMap:
        cntMap[v1] = 1
    else:
        cntMap[v1] += 1
    if v2 not in cntMap:
        cntMap[v2] = 1
    else:
        cntMap[v2] += 1

for i in range(n-1):
    v1, v2 = map(int, input().split())
    addCount(v1, v2)
    ab.append([v1, v2])
    nodeAidx = v1-1
    nodeBidx = v2-1
    nodeA = None
    nodeB = None
    if nodes[nodeAidx] is None:
        nodeA = Node(v1)
        nodes[nodeAidx] = nodeA
    else:
        nodeA = nodes[nodeAidx]
    if nodes[nodeBidx] is None:
        nodeB = Node(v2)
        nodes[nodeBidx] = nodeB
    else:
        nodeB = nodes[nodeBidx]
    nodeA.adj.append(nodeB)

#print(ab)
#print(nodes)
root = nodes[0]
nodes[1].pec = 1
q = deque()
q.append(root)

temp = list(cntMap.values())
temp.sort()
#maxV = 4 # TODO: FIX
maxV = temp[-1]
print(maxV)
while q:
    node = q.popleft()
    #print(node.val)
    pec = node.pec

    for i in range(len(node.adj)):
        a = node.adj[i]
        if pec < maxV:
            a.pec = pec + i + 1
        else:
            a.pec = pec - i - 1
        print(a.pec)
        q.append(a)

# for i in range(n):
#     # nodeA = ab[i][0]
#     # nodeB = ab[i][1]
#     node = nodes[i]
#     print(node.adj)

Submission status: Wrong Answer

Solution code:
N = int(input())
colors = [set() for i in range(N)]
ans = [-1] * N

max_color = 1
color = 1
for i in range(N - 1):
    a, b = map(int, input().split())
    for c in range(1, max_color + 2):
        if c in colors[a - 1] or c in colors[b - 1]:
            continue
        color = c
        break
    max_color = max(max_color, color)
    colors[a - 1].add(color)
    colors[b - 1].add(color)
    ans[i] = color

print(max_color)
for i in range(N - 1):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
n = int(input())
p = []
for i in range(n-1):
    p.append(list(map(int, input().split())))
color = [0 for i in range(n-1)]
Ncolor = [[] for i in range(n)]
for i, value in enumerate(p):
    color[i] = 1
    maxcolor = 1
    l = value[0]-1
    r = value[1]-1
    for j in range(10000000):
        if color[i] in Ncolor[l]:
            color[i] = color[i] + 1
        elif color[i] in Ncolor[r]:
            color[i] = color[i] + 1
        else:
            Ncolor[l].append(color[i])
            Ncolor[r].append(color[i])
            if maxcolor < color[i]:
                maxcolor = int(color[i])
            break
print(maxcolor)
for i in color:
    print(i)

Submission status: Wrong Answer

Solution code:
import sys, math

def input():
    return sys.stdin.readline()[:-1]

def main():
    N = int(input())
    T = []
    for k in range(N-1):
        a, b = map(int,input().split())
        T.append([a,b])
    C = [set([0]) for k in range(N+1)]
    ans = []
    for e in T:
        t = 0
        while (t in C[e[0]]) or (t in C[e[1]]):
            t += 1
        ans.append(t)
        C[e[0]].add(t)
        C[e[1]].add(t)
    print(max(ans))
    print(*ans,sep="\n")
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n=int(input())
graph=[[] for i in range(n)]
from collections import deque
for i in range(n-1):
    a,b=map(int,input().split())
    a-=1;b-=1
    graph[a].append(b)
    graph[b].append(a)
#print(graph)
num=[]
for i in range(len(graph)):
  num.append(len(graph[i]))
num_color=max(num)
start=num.index(num_color)
#print(start)
#print(num_color)

quest=deque([start])#はじめどうせ見るし入れとく
visited=[-1]*n
visited[start]=1
while len(quest)!=0:
    see=quest.popleft()
    for i in graph[see]:
        if visited[i]!=-1:
            continue
        quest.append(i)
        visited[i]=visited[see]+1
print(num_color)

for i in range(len(visited)):
  print(visited[i])

Submission status: Wrong Answer

Solution code:
N = int(input())
AB = [[int(x) for x in input().split()] for _ in range(N - 1)]

AB.sort(key=lambda x:x[1])
AB.sort(key=lambda x:x[0])
N_dict = {}
for i in range(N):
    N_dict[i + 1] = []

ans_list = []
for i in range(N - 1):
    j = 1
    while True:
        if j in N_dict[AB[i][0]] or j in N_dict[AB[i][0]]:
            j += 1
        else:
            ans_list.append(j)
            N_dict[AB[i][0]].append(j)
            N_dict[AB[i][1]].append(j)
            break
print(max(ans_list))
for i in range(N - 1):
    print(ans_list[i])

Submission status: Wrong Answer

Solution code:
#coding:utf-8
import sys
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = lambda *something : print(*something) if DEBUG else 0
DEBUG = False
def main(given = sys.stdin.readline):
    input = lambda : given().rstrip()
    LMIIS = lambda : list(map(int,input().split()))
    II = lambda : int(input())
    XLMIIS = lambda x : [LMIIS() for _ in range(x)]

    N = II()
    from collections import defaultdict
    num_c = defaultdict(int)
    E = defaultdict(lambda:defaultdict(int))
    inputE = []
    for i in range(N-1):
        ai,bi = LMIIS()
        if bi < ai:
            ai,bi = bi,ai
        num_c[ai] += 1
        num_c[bi] += 1
        E[ai][bi]= -1
        inputE.append((ai,bi))
    max_c = max(num_c.values())
    


    def colour(e1,e2,c):
        E[e1][e2] = c
        tmpc = 0
        for e22 in E[e2].keys():
            tmpc += 1
            if tmpc == c:
                tmpc +=  1
            colour(e2,e22,tmpc)

            
        pass

    colour(1,2,1)
    print(max_c)


    for ai,bi in inputE:
        print(E[ai][bi])



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
ab = [list(map(int, input().split())) for _ in range(N-1)]

kosu = [0] * N
hen = [0] * N
ans = [0] * (N-1)
for i in range(N-1):
    a = ab[i][0] - 1
    b = ab[i][1] - 1
    kosu[a] += 1
    kosu[b] += 1
    tmp = max(kosu[a], kosu[b])
    while True:
        if hen[a] == tmp or hen[b] == tmp:
            tmp += 1
        else:
            break
    ans[i] = tmp
    hen[a] = tmp
    hen[b] = tmp

K = max(kosu)
print(K)
for i in range(N-1):
    print(ans[i] % K + 1)

Submission status: Wrong Answer

Solution code:
N=int(input())
l=[[] for _ in range(N)]
for i in range(N-1):
  a,b = map(int,input().split())
  l[a-1].append(b)
  l[b-1].append(a)
res=[len(c) for c in l]
print(max(res))
print(l)

from collections import deque
check=[False] * N

que=deque([])
for a in l:
  if a:
    s=a
    break
que.append(a)
count=1
while que:
  y=que.popleft()
  count=1
  for k in y:
    if check[k-1]:
      count+=1
      continue
    else:
      check[k-1]=True
      count+=1
      print(count)
      que.append(l[k-1])

Submission status: Wrong Answer

Solution code:
ni = lambda: int(input())
nm = lambda: map(int, input().split())
nl = lambda: list(map(int, input().split()))

n = ni()

g = [[] for _ in range(n)]

for i in range(n-1):
  a, b = nm()
  g[a].append((a,b))

colors = [[] for _ in range(n+1)]
childcolors = [[] for _ in range(n+1)]
maxc = 0

for i in range(1, n):

  for j in range(len(g[i])):
    num = 1
    while True:
      if num not in colors[g[i][j][0]] and num not in childcolors[g[i][j][0]]:
        childcolors[g[i][j][0]].append(num)
        colors[g[i][j][1]].append(num)
        maxc = max(maxc, num)
        break
      num += 1

# print(childcolors)
# print(colors)

print(maxc)
for c in colors:
  if len(c) > 0:
    print(c[0])

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

N = int(input())
tree = [0]*N
ape = [set() for _ in range(N)]
hen = [0]*(N-1)
for i in range(N-1):
    a,b = map(int,input().split())
    tmp = 0
    #hen[i] = max(tree[a-1], tree[b-1])
    while True:
        if (tmp in ape[a-1]) or (tmp in ape[b-1]):
            tmp += 1
            continue
        else:
            hen[i] = tmp
            break
    ape[a-1].add(hen[i])
    ape[b-1].add(hen[i])
    tree[a-1] += 1
    tree[b-1] += 1
print(max(tree))
for i in range(N-1):
    print(hen[i]+1)

Submission status: Wrong Answer

Solution code:
# import bisect
n=int(input())
# n=100000
used_col={i:set() for i in range(n)}
col_list=[]
allcols = {i+1 for i in range(n)}
for i in range(n-1):
    a,b = map(int,input().split())
    # a=i+1
    # b=i+2
    a-=1
    b-=1
    a_used_col = used_col[a]
    b_used_col = used_col[b]
    for i in range(n):
        if i+1 in a_used_col or i+1 in b_used_col:
            continue
        c = i+1
        break
    col_list.append(c)
    used_col[a].add(c)
    used_col[b].add(c)
print(max(col_list))
for x in col_list:
    print(x)

Submission status: Wrong Answer

Solution code:
def two_int():
    N, K = map(int, input().split())
    return N,K

def one_int():
    return int(input())

def one_str():
    return input()

def many_int():
    return list(map(int, input().split()))

N=one_int()

tree ={ i+1:{} for i in range(N)}

alls={}

output=[]
for i in range(N-1):
    A,B=two_int()
    for i in range(1,N+1):
        if i not in tree[A] and i not in tree[B]:
            if i not in alls:
                alls[i]=1
            tree[A][i]=1
            tree[B][i]=1
            output.append(i)
            break

print(len(alls))
for i in output:
    print(i)