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: Time Limit Exceeded

Solution code:
"""Coloring Edges on Tree
https://atcoder.jp/contests/abc146/tasks/abc146_d
"""
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 5 + 1)

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


def dfs(node, p):
    # print(node.num, p)
    for e in node.edge:
        used_color = node.edge_color
        if e != p:
            # 子のノードを取得
            child = tree[e]
            child_used_color = child.edge_color

            # このnodeと子のノードでまだ使っていない色を特定
            unused_colors = list(set(colors) - set(used_color + child_used_color))
            if len(unused_colors) == 0:
                color_num = max(colors) + 1
                colors.append(color_num)
            else:
                color_num = unused_colors[0]

            # このノードと、子のノードに使用ずみの色をマーク
            node.edge_color.append(color_num)
            child.edge_color.append(color_num)

            # 答えを記録
            ans['{a} {b}'.format(a=node.num, b=child.num)] = color_num
            ans['{a} {b}'.format(a=child.num, b=node.num)] = color_num

            # 掘る
            dfs(child, node.num)


N = int(input())
ans = {}
colors = [1]

# treeの初期化
tree = []
edges = []
tree.append(Node(0))
for i in range(1, N + 1):
    tree.append(Node(i))
for i in range(N - 1):
    inp = input().split()
    edges.append(inp)
    a, b = map(int, inp)
    tree[a].edge.append(b)
    tree[b].edge.append(a)

dfs(tree[1], -1)


print(len(colors))
for e in edges:
    # print(e)
    print(str(ans.get(' '.join(e))))

Submission status: Time Limit Exceeded

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

color = {}
C = 0
forbidden = [set() for _ in range(n+1)]
for a, b in sorted(edges):
    for c in range(n):
        if c not in forbidden[a] and c not in forbidden[b]:
            forbidden[a].add(c)
            forbidden[b].add(c)
            color[(a, b)] = c
            C = max(C, c)
            break

print(C + 1)
for a, b in edges:
    print(color[(a, b)] + 1)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# abc146_d
import sys,time

#f = open("abc146_test.txt", "r", encoding="utf-8")
#input_line = f.readline().rstrip()     # 1行
#input_lines = f.readlines()   # 全行
#f.close()
#point_total = int(input_line)
point_total = int(input())
#input_lines = sys.stdin.readlines()

lines = []
n = 0
#for input_line in input_lines:
#    tmp = list(map(int, input_line.rstrip().split()))
#    tmp.append(n)
#    n += 1
#    lines.append(tmp)

while True:
    try:
        tmp = list(map(int, input().rstrip().split()))
        tmp.append(n)
        n += 1
        lines.append(tmp)
    except:
        break

lines.sort()
colors = [set() for i in range(point_total)]
color_set = set()

def new_color(point1, point2):
    point1_color = colors[point1-1]
    point2_color = colors[point2-1]
    total_color = point1_color.union(point2_color)
    dif_set = color_set - total_color
    if len(dif_set):
        #i = min(dif_set)
        for s in dif_set:
            i = s
            break
    else:
        i = len(color_set) + 1
    point1_color.add(i)
    point2_color.add(i)
    return [i, point1_color, point2_color]

line_colors = {}

for line in lines:
    p1 = line[0]
    p2 = line[1]
    new_colors = new_color(p1, p2)
    colors[p1-1] = new_colors[1]
    colors[p2-1] = new_colors[2]
    line_colors[line[2]] = new_colors[0]
    color_set.add(new_colors[0])

print(len(color_set))
for key in sorted(line_colors):
    print(line_colors[key])

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# abc146_d
import sys

#f = open("abc146_test.txt", "r", encoding="utf-8")
#input_line = f.readline().rstrip()     # 1行
#input_lines = f.readlines()   # 全行
#f.close()
#point_total = int(input_line)

point_total = int(input())
#input_lines = sys.stdin.readlines()

lines = []
n = 0
#for input_line in input_lines:
#    tmp = list(map(int, input_line.rstrip().split()))
#    tmp.append(n)
#    n += 1
#    lines.append(tmp)

while True:
    try:
        tmp = list(map(int, input().rstrip().split()))
        tmp.append(n)
        n += 1
        lines.append(tmp)
    except:
        break

lines.sort()
colors = [set() for i in range(point_total)]
color_set = set()

def new_color(point1, point2):
    point1_color = colors[point1-1]
    point2_color = colors[point2-1]
    total_color = point1_color.union(point2_color)
    dif_set = color_set - total_color
    if len(dif_set):
        i = min(dif_set)
    else:
        i = len(color_set) + 1
    point1_color.add(i)
    point2_color.add(i)
    return [i, point1_color, point2_color]

line_colors = {}

for line in lines:
    p1 = line[0]
    p2 = line[1]
    new_colors = new_color(p1, p2)
    colors[p1-1] = new_colors[1]
    colors[p2-1] = new_colors[2]
    line_colors[line[2]] = new_colors[0]
    color_set.add(new_colors[0])

print(len(color_set))
for key in sorted(line_colors):
    print(line_colors[key])

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# abc146_d
import sys

#f = open("abc146_test.txt", "r", encoding="utf-8")
#input_line = f.readline().rstrip()     # 1行
#input_lines = f.readlines()   # 全行
#f.close()
#point_total = int(input_line)

point_total = int(input())
#input_lines = sys.stdin.readlines()

lines = []
n = 0
#for input_line in input_lines:
#    tmp = list(map(int, input_line.rstrip().split()))
#    tmp.append(n)
#    n += 1
#    lines.append(tmp)

while True:
    try:
        tmp = list(map(int, input().rstrip().split()))
        tmp.append(n)
        n += 1
        lines.append(tmp)
    except:
        break

lines.sort()
colors = [set() for i in range(point_total)]
color_set = {1}

def new_color(point1, point2):
    point1_color = colors[point1-1]
    point2_color = colors[point2-1]
    total_color = point1_color.union(point2_color)
    i = 1
    while i in total_color:
        i += 1
    point1_color.add(i)
    point2_color.add(i)
    return [i, point1_color, point2_color]

line_colors = {}

for line in lines:
    p1 = line[0]
    p2 = line[1]
    new_colors = new_color(p1, p2)
    colors[p1-1] = new_colors[1]
    colors[p2-1] = new_colors[2]
    line_colors[line[2]] = new_colors[0]
    color_set.add(new_colors[0])

print(len(color_set))
for key in sorted(line_colors):
    print(line_colors[key])

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# abc146_d
import sys

#f = open("abc146_test.txt", "r", encoding="utf-8")
#input_line = f.readline().rstrip()     # 1行
#input_lines = f.readlines()   # 全行
#f.close()
#point_total = int(input_line)

point_total = int(input())
input_lines = sys.stdin.readlines()

lines = []
n = 0
for input_line in input_lines:
    tmp = list(map(int, input_line.rstrip().split()))
    tmp.append(n)
    n += 1
    lines.append(tmp)

lines.sort()
colors = [set() for i in range(point_total)]
color_set = {1}

def new_color(point1, point2):
    point1_color = colors[point1-1]
    point2_color = colors[point2-1]
    total_color = point1_color.union(point2_color)
    i = 1
    while i in total_color:
        i += 1
    point1_color.add(i)
    point2_color.add(i)
    return [i, point1_color, point2_color]

line_colors = {}

for line in lines:
    p1 = line[0]
    p2 = line[1]
    new_colors = new_color(p1, p2)
    colors[p1-1] = new_colors[1]
    colors[p2-1] = new_colors[2]
    line_colors[line[2]] = new_colors[0]
    color_set.add(new_colors[0])

print(len(color_set))
for key in sorted(line_colors):
    print(line_colors[key])

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
G = [[] for i in range(n)]
root = 0
color_num = 0
keys = []

def get_key(n1, n2):
  if n1 > n2:
    return str(n2) + '-' + str(n1)
  return str(n1) + '-' + str(n2)

for _ in range(n - 1):
  a, b = map(int, input().split())
  keys.append(get_key(a - 1, b - 1))
  G[a - 1].append(b - 1)
  G[b - 1].append(a - 1)
  if color_num < len(G[a - 1]):
    root = a - 1
    color_num = len(G[a - 1])
  elif color_num < len(G[b - 1]):
    root = b - 1
    color_num = len(G[b - 1])

# print(G)
# [[1], [0, 2, 3, 4], [1], [1, 6], [1, 5], [4, 7], [3], [5]]
# print(root) # 最も多い色を持つノードの番号
print(color_num)  # 必要な最小色数
queue = [root]
checked = set()
result = {}

min_colors = [set(range(color_num)) for i in range(n)]

while len(queue) > 0:
  node = queue.pop(0)
  # print(node + 1)
  # ks = list(range(color_num))
  # print(node)
  # print(ks)
  # for node2 in G[node]:
  #   key = get_key(node, node2)
  #   if key in result:
  #     ks.pop(result[key])
  for node2 in G[node]:
    if node2 not in checked:
      key = get_key(node, node2)
      # result[key] = ks.pop(0)
      result[key] = min_colors[node].pop()
      min_colors[node2].discard(result[key])
      queue.append(node2)
  checked.add(node)

for k in keys:
  print(result[k] + 1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
 
n = int(input())
node_list = []
nodes = [[] for _ in range(n)]
edges = dict()
for _ in range(n - 1):
	a, b = 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])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
node_list = []
nodes = [[] for _ in range(n)]
edges = dict()
for _ in range(n - 1):
	a, b = 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 = [False] * n
que = deque()
que.append(0)
while len(que) > 0:
	ni = que.pop()
	if used[ni]:
		continue
	used_colors = [edges[tuple(sorted((ni, e)))] for e in nodes[ni]]
	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:
					break
			# print((a, b), color)
			edges[(a, b)] = color
			used_colors.append(color)
		que.append(node)

	used[ni] = True

print(max(edges.values()))
for node in node_list:
	print(edges[node])

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
input = sys.stdin.readline

n = int(input())
node_list = []
nodes = [[] for _ in range(n)]
edges = dict()
for _ in range(n - 1):
	a, b = 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 = [False] * n
que = deque()
que.append(0)
while len(que) > 0:
	ni = que.pop()
	if used[ni]:
		continue
	used_colors = [edges[tuple(sorted((ni, e)))] for e in nodes[ni]]
	unused = deque([c for c in range(n, 0, -1) if not c in used_colors])
	for node in nodes[ni]:
		[a, b] = sorted([ni, node])
		if edges[(a, b)] == 0:
			edges[(a, b)] = unused.pop()
		que.append(node)

	used[ni] = True

print(max(edges.values()))
for node in node_list:
	print(edges[node])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
node_list = []
nodes = [[] for _ in range(n)]
edges = dict()
for _ in range(n - 1):
	a, b = 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 = [False] * n
que = deque()
que.append(0)
while len(que) > 0:
	ni = que.pop()
	if used[ni]:
		continue
	used_colors = [edges[tuple(sorted((ni, e)))] for e in nodes[ni]]
	unused = deque([c for c in range(n, 0, -1) if not c in used_colors])
	for node in nodes[ni]:
		[a, b] = sorted([ni, node])
		if edges[(a, b)] == 0:
			# print((a, b), unused)
			edges[(a, b)] = unused.pop()
			# print(edges[(a, b)])
		que.append(node)

	used[ni] = True

print(max(edges.values()))
for node in node_list:
	print(edges[node])

Submission status: Time Limit Exceeded

Solution code:
n=int(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])

Submission status: Time Limit Exceeded

Solution code:
n=int(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 aa[i] and k not in 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])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
nodes = [[] for _ in range(n)]
edges = []
colors = [0] * (n - 1)
for _ in range(n - 1):
	a, b = map(int, input().split())
	nodes[a - 1].append(b - 1)
	nodes[b - 1].append(a - 1)
	edges.append((a - 1, b - 1))

used = [False] * n
que = deque()
que.append(0)
while len(que) > 0:
	ni = que.pop()
	if used[ni]:
		continue
	color = 1
	used_colors = []
	unused = []
	for e in nodes[ni]:
		[a, b] = sorted([e, ni])
		used_colors.append(colors[edges.index((a, b))])
	unused = [c for c in range(1, n + 1) if not c in used_colors]
	for node in nodes[ni]:
		[a, b] = sorted([ni, node])
		# print(a, b)
		ci = edges.index((a, b))
		if colors[ci] == 0:
			# print(ni, unused)
			color = min(unused)
			colors[ci] = color
			unused = unused[1:]
		que.append(node)

	used[ni] = True

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

Submission status: Time Limit Exceeded

Solution code:

#%%
import sys
def input():
    return sys.stdin.readline().rstrip()

def main():
    N = int(input())
    As = [tuple(map(int, input().split())) for _ in range(N-1)]

    m = [[0 for _ in range(N)] for _ in range(N)]
    for u, v in As:
        m[u-1][v-1] = 1
        m[v-1][u-1] = 1

    n_e = max([l.count(1) for l in m])
    print(n_e)

    ans = [[0 for _ in range(N)] for _ in range(N)]

    def dfs(u, c0):
        c = c0
        for v in range(N):
            if m[u][v]:
                m[u][v]=0
                m[v][u]=0
                c = c%n_e + 1
                ans[u][v] = c
                ans[v][u] = c
                dfs(v, c)

    dfs(0, 0)

    for u, v in As:
        print(ans[u-1][v-1])



# %%
if __name__ == '__main__':
    main()

# %%
# from atcoder_test import doTest
# doTest("abc146","d",main)

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
input=sys.stdin.readline
def sol():
    n=int(input())
    x=[set([]) for i in range(n+1)]
    z=[i for i in range(1,n)]
    ans=[0]*(n-1)
    w=[]
    d={}
    for i in range(n-1):
        a,b=map(int,input().split())
        heapq.heappush(w,(a,b,i))
    p=0
    q=1
    for hhh in range(len(w)):
        a,b,h=heapq.heappop(w)
        if a!=p:
            for i in z:
                if i not in x[a]:
                    q=i
                    p=a
                    break
        for j in range(q,n):
            if j not in x[a] and j not in x[b]:
                ans[h]+=j
                x[a].add(j)
                x[b].add(j)
                break
    print(max(ans))
    print(*ans)
    #for i in ans:
    #    print(i)

if __name__=="__main__":
    sol()

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
input=sys.stdin.readline
def sol():
    n=int(input())
    x=[set([]) for i in range(n+1)]
    z=[i for i in range(1,n)]
    ans=[0]*(n-1)
    w=[]
    d={}
    for i in range(n-1):
        a,b=map(int,input().split())
        heapq.heappush(w,(a,b,i))
    p=0
    q=1
    for hhh in range(len(w)):
        a,b,h=heapq.heappop(w)
        if a!=p:
            for i in z:
                if i not in x[a]:
                    q=i
                    p=a
                    break
        for j in range(q,n):
            if j not in x[a] and j not in x[b]:
                ans[h]+=j
                x[a].add(j)
                x[b].add(j)
                break
    print(max(ans))
    for i in ans:
        print(i)

if __name__=="__main__":
    sol()

Submission status: Time Limit Exceeded

Solution code:

#%%
import sys
def input():
    return sys.stdin.readline().rstrip()

import numpy as np

def main():
    N = int(input())
    As = [tuple(map(int, input().split())) for _ in range(N-1)]

    m = np.array([[0 for _ in range(N)] for _ in range(N)], dtype=int)
    for a, b in As:
        m[a-1][b-1] = 1
        m[b-1][a-1] = 1

    ans = np.array([[0 for _ in range(N)] for _ in range(N)], dtype=int)

    from collections import deque

    max_c = 1
    l = deque([(0,0)])
    while (len(l)):
        v0, c0 = l.popleft()
        c1 = 1
        for v1 in range(N):
            if m[v0][v1]:
                m[v0][v1] = 0
                m[v1][v0] = 0
                if c1 == c0:
                    c1 += 1
                max_c = max(max_c, c1)
                ans[v0][v1] = c1
                ans[v1][v0] = c1
                l.append((v1, c1))
                c1 += 1

    print(max_c)
    for u, v in As:
        print(ans[u-1][v-1])



# %%
if __name__ == '__main__':
    main()

# %%
# from atcoder_test import doTest
# doTest("abc146","d",main)

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
input=sys.stdin.readline
def sol():
    n=int(input())
    x=[set([]) for i in range(n+1)]
    ans=[0]*(n-1)
    w=[]
    d={}
    for i in range(n-1):
        a,b=map(int,input().split())
        #a2,b2=max(a,b),min(a,b)
        heapq.heappush(w,(a,b,i))
        #if a2 not in d:
        #    d[a2]=set([(b2,i)])
        #else:
        #    d[a2].add((b2,i))
    #for i in d:
    #    heapq.heappush(w,(-len(d[i]),i))
    for hhh in range(len(w)):
        a,b,h=heapq.heappop(w)
        #for b,h in d[a]:
        for j in range(1,n):
            if j not in x[a] and j not in x[b]:
                ans[h]+=j
                x[a].add(j)
                x[b].add(j)
                break
    print(max(ans))
    for i in ans:
        print(i)

if __name__=="__main__":
    sol()

Submission status: Time Limit Exceeded

Solution code:

#%%
import sys
def input():
    return sys.stdin.readline().rstrip()

def main():
    N = int(input())
    As = [tuple(map(int, input().split())) for _ in range(N-1)]

    m = [[0 for _ in range(N)] for _ in range(N)]
    for a, b in As:
        m[a-1][b-1] = 1
        m[b-1][a-1] = 1

    ans = [[0 for _ in range(N)] for _ in range(N)]

    from collections import deque

    max_c = 1
    l = deque([(0,0)])
    while (len(l)):
        v0, c0 = l.popleft()
        c1 = 1
        for v1 in range(N):
            if m[v0][v1]:
                m[v0][v1] = 0
                m[v1][v0] = 0
                if c1 == c0:
                    c1 += 1
                max_c = max(max_c, c1)
                ans[v0][v1] = c1
                ans[v1][v0] = c1
                l.append((v1, c1))
                c1 += 1

    print(max_c)
    for u, v in As:
        print(ans[u-1][v-1])



# %%
if __name__ == '__main__':
    main()

# %%
# from atcoder_test import doTest
# doTest("abc146","d",main)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
G = [[] for i in range(n)]
root = 0
color_num = 0
keys = []

def get_key(n1, n2):
  if n1 > n2:
    return str(n2) + '-' + str(n1)
  return str(n1) + '-' + str(n2)

for _ in range(n - 1):
  a, b = map(int, input().split())
  keys.append(get_key(a - 1, b - 1))
  G[a - 1].append(b - 1)
  G[b - 1].append(a - 1)
  if color_num < len(G[a - 1]):
    root = a - 1
    color_num = len(G[a - 1])
  elif color_num < len(G[b - 1]):
    root = b - 1
    color_num = len(G[b - 1])

# print(G)
# [[1], [0, 2, 3, 4], [1], [1, 6], [1, 5], [4, 7], [3], [5]]
# print(root) # 最も多い色を持つノードの番号
print(color_num)  # 必要な最小色数
queue = [root]
checked = set()
result = {}

while len(queue) > 0:
  node = queue.pop(0)
  # print(node + 1)
  ks = list(range(color_num))
  for node2 in G[node]:
    key = get_key(node, node2)
    if key in result:
      ks.pop(result[key])
  for node2 in G[node]:
    if node2 not in checked:
      key = get_key(node, node2)
      result[key] = ks.pop(0)
      queue.append(node2)
  checked.add(node)

for k in keys:
  print(result[k] + 1)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
G = [[] for i in range(n)]
nodes = {}
root = 0
color_num = 0
keys = []

def get_key(n1, n2):
  if n1 > n2:
    return str(n2) + '-' + str(n1)
  return str(n1) + '-' + str(n2)

for _ in range(n - 1):
  a, b = map(int, input().split())
  keys.append(get_key(a - 1, b - 1))
  G[a - 1].append(b - 1)
  G[b - 1].append(a - 1)
  if a in nodes:
    nodes[a] += 1
  else:
    nodes[a] = 1
  if b in nodes:
    nodes[b] += 1
  else:
    nodes[b] = 1
# ex. {1: 1, 2: 4, 3: 1, 4: 2, 5: 2, 6: 2, 7: 1, 8: 1}
# print(nodes)
# print(G)
for i, g in enumerate(G):
  if color_num < len(g):
    root = i
    color_num = len(g)

# [[1], [0, 2, 3, 4], [1], [1, 6], [1, 5], [4, 7], [3], [5]]
# print(root) # 最も多い色を持つノードの番号
print(color_num) # 必要な最小色数
queue = [root]
checked = set()
result = {}

while len(queue) > 0:
  node = queue.pop(0)
  # print(node + 1)
  ks = list(range(color_num))
  for node2 in G[node]:
    key = get_key(node, node2)
    if key in result:
      ks.pop(result[key])
  for node2 in G[node]:
    if node2 not in checked:
      key = get_key(node, node2)
      result[key] = ks.pop(0)
      queue.append(node2)
  checked.add(node)

for k in keys:
  print(result[k] + 1)

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
input=sys.stdin.readline
def sol():
    n=int(input())
    x=[set([]) for i in range(n+1)]
    #z=[i for i in range(1,n)]
    #hhh=[1]*(n+1)
    ans=[0]*(n-1)
    w=[]
    d={}
    for i in range(n-1):
        a,b=map(int,input().split())
        #a2,b2=min(a,b),max(a,b)
        a2,b2=max(a,b),min(a,b)
        if a2 not in d:
            d[a2]=set([(b2,i)])
        else:
            d[a2].add((b2,i))
    for i in d:
        heapq.heappush(w,(-len(d[i]),i))
    y=[0]*2
    #for a,b,p in w:
    while len(w):
        h1,a=heapq.heappop(w)
        for b,h in d[a]:
            #c=x[a]|x[b]
            #if y[0]!=a:
            #    for i in z:
            #        if i not in c:
            #            y[0]=a
            #            y[1]=i
            #            break
            #for j in range(y[1],n+1):
            for j in range(1,n+1):
                if j not in x[a] and j not in x[b]:
                    ans[h]+=j
                    x[a].add(j)
                    x[b].add(j)
                    #if y[1]+1==j: y[1]+=1
                    break
    print(max(ans))
    for i in ans:
        print(i)

if __name__=="__main__":
    sol()

Submission status: Time Limit Exceeded

Solution code:

#%%
import sys
def input():
    return sys.stdin.readline().rstrip()

def main():
    N = int(input())
    As = [tuple(map(int, input().split())) for _ in range(N-1)]

    m = [[0 for _ in range(N)] for _ in range(N)]
    for u, v in As:
        m[u-1][v-1] = 1
        m[v-1][u-1] = 1

    n_e = max([l.count(1) for l in m])
    print(n_e)

    ans={}

    def dfs(u, c0):
        c = c0
        for v in range(N):
            if m[u][v]:
                m[u][v]=0
                m[v][u]=0
                c = c%n_e + 1
                ans[(u+1, v+1)] = c
                dfs(v, c)

    dfs(0, 0)

    for u, v in As:
        print(ans[(u, v)])



# %%
if __name__ == '__main__':
    main()

# %%
# from atcoder_test import doTest
# doTest("abc146","d",main)

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
input=sys.stdin.readline
def sol():
    n=int(input())
    x=[set([]) for i in range(n+1)]
    #z=[i for i in range(1,n)]
    #hhh=[1]*(n+1)
    ans=[0]*(n-1)
    w=[]
    d={}
    for i in range(n-1):
        a,b=map(int,input().split())
        #a2,b2=min(a,b),max(a,b)
        a2,b2=max(a,b),min(a,b)
        if a2 not in d:
            d[a2]=set([(b2,i)])
        else:
            d[a2].add((b2,i))
    for i in d:
        heapq.heappush(w,(-len(d[i]),i))
    y=[0]*2
    #for a,b,p in w:
    while len(w):
        h1,a=heapq.heappop(w)
        for b,h in d[a]:
            c=x[a]|x[b]
            #if y[0]!=a:
            #    for i in z:
            #        if i not in c:
            #            y[0]=a
            #            y[1]=i
            #            break
            #for j in range(y[1],n+1):
            for j in range(1,n+1):
                if j not in c:
                    ans[h]+=j
                    x[a].add(j)
                    x[b].add(j)
                    #if y[1]+1==j: y[1]+=1
                    break
    print(max(ans))
    for i in ans:
        print(i)

if __name__=="__main__":
    sol()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
graph = [[] for i in range(N)]
basho = {}
for i in range(N-1):
    a, b = map(int, input().split())
    a, b = a-1, b-1
    graph[a].append(b)
    graph[b].append(a)
    s = str(a) + '-' + str(b)
    basho[s] = i
#print(basho)
#print(graph)
maxi = 0
root = -1
for i in range(N):
    leni = len(graph[i])
    maxi = max(leni, maxi)
    if maxi == leni:
        root = i

K = maxi
visited = [False for i in range(N)]
color = [0 for i in range(N)]
bashocolor = [0 for i in range(N-1)]
def bfs(v):
    Q = []
    visited[v] = True
    Q.append(v)
    while Q:
        v = Q.pop()
        clist = [i for i in range(1, K+1)]
        clist = list(set(clist) - set([color[v]]))
        now = 0
        for u in graph[v]:
            if not visited[u]:
                visited[u] = True
                color[u] = clist[now]
                now += 1
                if u > v:
                    nnn = str(v) + '-' + str(u)
                else:
                    nnn = str(u) + '-' + str(v)
                bashocolor[basho[nnn]] = color[u]
                Q.append(u)
bfs(root)
print(K)
for i in range(N-1):
    print(bashocolor[i])

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
def sol():
    n=int(input())
    x=[set([]) for i in range(n+1)]
    z=[i for i in range(1,n)]
    #hhh=[1]*(n+1)
    ans=[0]*(n-1)
    w=[]
    d={}
    for i in range(n-1):
        a,b=map(int,input().split())
        #a2,b2=min(a,b),max(a,b)
        a2,b2=max(a,b),min(a,b)
        if a2 not in d:
            d[a2]=set([b2])
        else:
            d[a2].add(b2)
        w.append((min(a,b),max(a,b),i))
    w.sort()
    y=[0]*2
    for a,b,p in w:
        c=x[a]|x[b]
        if y[0]!=a:
            for i in z:
                if i not in c:
                    y[0]=a
                    y[1]=i
                    break
        for j in range(y[1],n+1):
            if j not in c:
                ans[p]+=j
                x[a].add(j)
                x[b].add(j)
                if y[1]+1==j: y[1]+=1
                break
    print(max(ans))
    for i in ans:
        print(i)

if __name__=="__main__":
    sol()

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
def sol():
    n=int(input())
    x=[set([0]) for i in range(n+1)]
    #z=set([i for i in range(1,n+1)])
    z=[i for i in range(1,n)]
    #hhh=[1]*(n+1)
    ans=[0]*(n-1)
    w=[]
    for i in range(n-1):
        a,b=map(int,input().split())
        w.append((min(a,b),max(a,b),i))
    w.sort()
    y=[0]*2
    for a,b,p in w:
        c=x[a]|x[b]
        if y[0]!=a:
            for i in z:
                if i not in c:
                    y[0]=a
                    y[1]=i
                    break
        for j in range(y[1],n+1):
            if j not in c:
                ans[p]+=j
                x[a].add(j)
                x[b].add(j)
                if y[1]+1==j: y[1]+=1
                break
    print(max(ans))
    for i in ans:
        print(i)

if __name__=="__main__":
    sol()