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:
iro = []
res = []
r = 0

N = int(input())
for i in range(N-1):
  a,b = input().split(" ")
  a = int(a)
  b = int(b)
  cr = 0
  for p in iro:
    if a not in p and b not in p:
      iro[cr].append(a)
      iro[cr].append(b)
      res.append(cr+1)
      break
    cr += 1
  else:
    r = cr
    iro.append([a,b])
    res.append(cr+1)
print(r+1)
for i in res:
  print(i)

Submission status: Time Limit Exceeded

Solution code:
import collections
N=int(input())
AB=[list(map(int,input().split())) for i in range(N-1)]
AB_C=[0 for i in range(N-1)]
D=collections.Counter([i[0] for i in AB]+[i[1] for i in AB]).most_common()
M=D[0][1]
print(M)




data=[set() for i in range(N+1)]
idxdata=set([i for i in range(N-1)])
d=0
while idxdata or d<=2:
    #print(idxdata)
    count_c=1
    delidx=set()
    for i in idxdata:
        a,b=AB[i]
        if a==D[d][0] or b==D[d][0]:
            while not(count_c not in data[a] and count_c not in data[b]):
                count_c+=1
            AB_C[i]=count_c
            data[a].add(count_c)
            data[b].add(count_c)
            delidx.add(i)
    d+=1
    idxdata=idxdata-delidx




for i in idxdata:
    a,b=AB[i]
    #print(a,b,"a,b")
    for m in range(1,M+1):
        if m not in data[a] and m not in data[b]:
            data[a].add(m)
            data[b].add(m)
            print(m)
            break


for i in AB_C:
    print(i)

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
for i in range(N):
    leni = len(graph[i])
    maxi = max(leni, maxi)
K = maxi
color = {}
for i in range(N):
    v = graph[i]
    colk = [False for nnn in range(K)]
    NN = []
    for j in v:
        if i < j:
            n = str(i) + '-' + str(j)
        else:
            n = str(j) + '-' + str(i)
        NN.append(n)
    for s in NN:
        if basho[s] in color.keys():
            colk[color[basho[s]] - 1] = True
    for s in NN:
        if not basho[s] in color.keys():
            ind = colk.index(False)
            color[basho[s]] = ind + 1
            colk[ind] = True

print(K)
for i in range(N-1):
    print(color[i])

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
V = [[] for _ in range(N)]
E = dict()
yobidasi = []
for i in range(N - 1):
	a, b = 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]])

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(4100000)
N = int(input())
tree = [[] for _ in range(N+1) ]
already_make = [-1]*(N+1)
for i in range(1,N):
    a,b = 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)

Submission status: Time Limit Exceeded

Solution code:
import copy

n=int(input())
org=[i for i in range(1,10**5)]
org_set=set(org)
edges=[]
colors=[]
for i in range(n-1):
    a,b=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)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
AB = [list(map(int, input().split())) for _ in range(N-1)]
es = [[] for _ in range(N)]
color = [[] for _ in range(N)]
ans = {(a-1, b-1):0 for a, b in AB}
for a, b in AB:
    es[a-1].append(b-1)
    es[b-1].append(a-1)
K = 0
ind = 0
for i, e in enumerate(es):
    if K < len(e):
        K = len(e)
        ind = i
for i, c in zip(es[ind], range(K)):
    ans[(min(i, ind), max(i, ind))] = c + 1
    color[i].append(c+1)
    color[ind].append(c+1)


class Queue:
    def __init__(self):
        self.queue = []
    # 先頭にデータを追加
    def add(self,x):
        self.queue.append(x)
    # 最後のデータを削除
    def remove(self):
        del self.queue[0]
    # 最後のデータを返す
    def peek(self):
        return self.queue[0]
    # 空かどうか確認
    def is_empty(self):
        return len(self.queue) == 0

# 幅優先探索
def bfs(graph,start, s):
    mark_dict = {}
    queue = Queue()
    queue.add(start)
    while queue.is_empty() == False:
        target = queue.peek()
        queue.remove()
        if target not in mark_dict:
            mark_dict[target] = True
            for elem in graph[target]:
                queue.add(elem)
                if ans[(min(target, elem), max(target, elem))] == 0:
                    c_rest = s - (set(color[target]) | set(color[elem]))
                    c_rest = c_rest.pop()
                    ans[(min(target, elem), max(target, elem))] = c_rest
                    color[target].append(c_rest)
                    color[elem].append(c_rest)
bfs(es, ind, set(range(1, K+1)))
print(K)
for a, b in AB:
    print(ans[(a-1, b-1)])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def bfs(succs, preds, start, colors):
    saisyoku = {}
    queue = deque([start])
    while queue:
        v = queue.popleft()
        color_v = colors.copy()
        for u in preds[v]:
            color_v.remove(saisyoku[preds[v][u]])
        for w in succs[v]:
            saisyoku[succs[v][w]] = color_v.pop()
            queue.append(w)
    return saisyoku

n = int(input())
vertices = range(1, n+1)
edges = [list(map(int, input().split())) for _ in range(n-1)]
jisu = {v: 0 for v in vertices}
succs = {v: {} for v in vertices}
preds = {v: {} for v in vertices}
for i, (u, v) in enumerate(edges):
  succs[u][v] = i
  preds[v][u] = i
  jisu[u] += 1
  jisu[v] += 1
#print(succs)
#print(preds)
color_num = max(jisu.values())
print(color_num)
colors = list(range(1, color_num+1))
saisyoku = bfs(succs, preds, 1, colors)
for _, c in sorted(saisyoku.items()):
    print(c)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
AB = [list(map(int, input().split())) for _ in range(N-1)]
es = [[] for _ in range(N)]
color = [[] for _ in range(N)]
ans = {(a-1, b-1):0 for a, b in AB}
for a, b in AB:
    es[a-1].append(b-1)
    es[b-1].append(a-1)
K = 0
ind = 0
for i, e in enumerate(es):
    if K < len(e):
        K = len(e)
        ind = i
for i, c in zip(es[ind], range(K)):
    ans[(min(i, ind), max(i, ind))] = c + 1
    color[i].append(c+1)
    color[ind].append(c+1)


class Queue:
    def __init__(self):
        self.queue = []
    # 先頭にデータを追加
    def add(self,x):
        self.queue.append(x)
    # 最後のデータを削除
    def remove(self):
        del self.queue[0]
    # 最後のデータを返す
    def peek(self):
        return self.queue[0]
    # 空かどうか確認
    def is_empty(self):
        return len(self.queue) == 0

# 幅優先探索
def bfs(graph,start, s):
    mark_dict = {}
    queue = Queue()
    queue.add(start)
    while queue.is_empty() == False:
        target = queue.peek()
        queue.remove()
        if target not in mark_dict:
            mark_dict[target] = True
            for elem in graph[target]:
                queue.add(elem)
                if ans[(min(target, elem), max(target, elem))] == 0:
                    c_rest = s - (set(color[target]) | set(color[elem]))
                    c_rest = c_rest.pop()
                    ans[(min(target, elem), max(target, elem))] = c_rest
                    color[target].append(c_rest)
                    color[elem].append(c_rest)
bfs(es, ind, set(range(1, K+1)))
print(K)
for a, b in AB:
    print(ans[(a-1, b-1)])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def bfs(succs, preds, start, colors):
    saisyoku = {}
    queue = deque([start])
    while queue:
        v = queue.popleft()
        color_v = colors.copy()
        for u in preds[v]:
            color_v.remove(saisyoku[preds[v][u]])
        for w in succs[v]:
            saisyoku[succs[v][w]] = color_v.pop(0)
            queue.append(w)
    return saisyoku

n = int(input())
vertices = range(1, n+1)
edges = [list(map(int, input().split())) for _ in range(n-1)]
jisu = {v: 0 for v in vertices}
succs = {v: {} for v in vertices}
preds = {v: {} for v in vertices}
for i, (u, v) in enumerate(edges):
  succs[u][v] = i
  preds[v][u] = i
  jisu[u] += 1
  jisu[v] += 1
#print(succs)
#print(preds)
color_num = max(jisu.values())
print(color_num)
colors = list(range(1, color_num+1))
saisyoku = bfs(succs, preds, 1, colors)
for _, c in sorted(saisyoku.items()):
    print(c)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
#abc146_d
import sys
import math
import collections
#sys.setrecursionlimit(100000)

n=int(input())

ai=[]
bi=[]
count = [0 for i in range(n+1)]

#print(count)
for i in range(n-1):
	tmp = input().split()
	a,b = list(map(lambda a: int(a), tmp))
	ai.append(a)
	bi.append(b)
	count[a]+=1
	count[b]+=1
#print(count)

maxapexcount=count[1]
maxapexno=1
for i in range(n+1):
	if(count[i]>maxapexcount):
		maxapexcount=count[i]
		maxapexno=i
print(maxapexcount)





listtmp = [[0 for i in range(n+1)] for j in range(n+1)]
k=0
for i in range(n-1):
	for j in range(1,n):
		if(listtmp[ai[i]][j]!=1)and(listtmp[bi[i]][j]!=1):
			listtmp[ai[i]][j]=1
			listtmp[bi[i]][j]=1
			print(j)
			break

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(5 * 10**5)
input = sys.stdin.readline

N = int(input())

M = [[0 for i in range(N)] for j in range(N)]
L = [list() for j in range(N)]

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

ans = [0] * N


def roop(target, parent, num):
    l = L[target]
    l.remove(parent)

    col = 1
    for t in l:
        if col == num:
            col += 1
        ans[M[target][t]] = col
        roop(t, target, col)
        col += 1


for i, t in enumerate(L[0]):
    ans[M[0][t]] = i + 1
    roop(t, 0, i + 1)

ans.pop(0)
print(max(ans))
for a in ans:
    print(a)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
edge_idx = {}
edge_color = {i: None for i in range(N-1)}
E = {v: [] for v in range(1, N+1)}
for i in range(N-1):
    a, b = map(int, input().split())
    edge_idx[(a, b)] = i
    E[a].append(b)
    E[b].append(a)
degs = {v: 0 for v in range(1, N+1)}
for v in range(1, N + 1):
    E[v].sort()
    degs[v] = len(E[v])
K = max(degs.values())
print(K)
for v in range(1, N):
    available = set(range(1, K+1))
    for u in E[v]:
        if v > u:
            e_idx = edge_idx[(u, v)]
            available -= set([edge_color[e_idx]])
            continue
        e_idx = edge_idx[(v, u)]
        c = list(available)[0]
        edge_color[e_idx] = c
        available -= set([c])
for i in range(N-1):
    print(edge_color[i])

Submission status: Time Limit Exceeded

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)
    for b, c in zip(t_list, t_color):
        # print(a, b, c)
        color[a][c] = True
        color[b][c] = True
        ans_c[min(a, b), max(a, b)] = c
        dfs(visit, b, a, c)

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

Solution code:
from collections import deque
N = int(input())
E = [tuple(map(lambda x:int(x)-1, input().split())) for _ in range(N-1)]
K = 0
E_sorted = sorted(E, key=lambda x:x[0])
ans = {}
V = [deque([i for i in range(1, N)]) for _ in range(N)]
for e in E_sorted:
  a, b = e
  c = 1
  req_K = True
  c = V[a].popleft()
  if c > K:
    K = c
  V[b].remove(c)
  ans[e] = c
print(K)
for e in E:
  print(ans[e])

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
from collections import Counter
c = [0]*n
arr = []
ans = [set() for i in range(n)]
for i in range(n-1):
    a,b = map(int,input().split())
    c[a-1] += 1
    c[b-1] += 1
    arr.append([i,a-1,b-1])
color = max(c)
print(color)
cnt = 1
for i,j,k in arr:
    while(1):
        cnt %= color
        cnt += 1
        if cnt not in ans[j] and cnt not in ans[k]:
            print(cnt)
            ans[j].add(cnt)
            ans[k].add(cnt)
            break

Submission status: Time Limit Exceeded

Solution code:
def main():
    n=int(input())
    a=[0]*(n-1)
    b=[0]*(n-1)
    for i in range(n-1):
        a[i],b[i] = map(int,input().split())
    import collections
    k=collections.Counter(a+b).most_common()[0][1]
    color_list=list(range(k))
    
    tree=[[] for _ in range(n)]
    for i in range(n-1):
        tree[a[i]-1].append(b[i])
        tree[b[i]-1].append(a[i])
        
    used_colors=[[] for _ in range(n)]
    ans=dict()
    q = [(1,0)]
#    while q:
    for _ in range(n):
        x,parent = q.pop()
        if parent!=0:
            for i in color_list:
                if not i in used_colors[parent-1]:
                    current_color=i
                    break
            used_colors[parent-1].append(current_color)
            used_colors[x-1].append(current_color)
        
            ans[str(parent)+"_"+str(x)]=current_color
        for y in tree[x-1]:
            if y == parent:
                continue
            q.append((y,x))
    
    print(k)
    for i in range(n-1):
        s=str(a[i])+"_"+str(b[i])
        print(ans[s]+1)
    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
to = [[] for _ in range(N)]
E = []
for _ in range(N-1):
    a, b = map(int,input().split())
    a -= 1
    b -= 1
    E.append((a,b))
    to[a].append(b)
    to[b].append(a)

K = 0
for i in range(N):
    K = max(K, len(to[i]))

print(K)

color = [[-1] * N for _ in range(N)]
def dfs(P, C, parent):
    c = 1
    for i in to[P]:
        if i == parent:
            continue
        if c == C:
            c += 1
        color[P][i] = c
        color[i][P] = c
        dfs(i, c, P)
        c += 1

dfs(0, 0, -1)

for i in E:
    print(color[i[0]][i[1]])

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
import bisect
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop


def LI(): return [int(x) for x in sys.stdin.readline().split()]


def I(): return int(sys.stdin.readline())


def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res


def IR(n):
    return [I() for i in range(n)]


# A
def A():
    s = input()
    if s == 'SUN':
        print(7)
    if s == "MON":
        print(6)
    if s == "TUE":
        print(5)
    if s == "WED":
        print(4)
    if s == "THU":
        print(3)
    if s == "FRI":
        print(2)
    if s == "SAT":
        print(1)
    return


# B
def B():
    al = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    n = I()
    s = S()
    for i in range(len(s)):
        ni = (al.index(s[i]) + n) % 26
        s[i] = al[ni]
    print(''.join(s))
    return


# C
def C():
    a, b, x = LI()
    l = [a * (10 ** (i - 1)) + b * i for i in range(1, 11)]
    p = 0
    for i in range(10):
        if x < l[i] and i == 0:
            print(0)
            return
        if l[i] <= x and i == 9:
            print(10 ** 9)
            return
        elif l[i] <= x < l[i + 1]:
            p = i + 1
            break
    if (x - b * p) // a >= 10 ** p:
        print(10 ** p - 1)
    else:
        print((x - b * p) // a)
    return


# D
def D():
    n = I()
    ab = [LI() for i in range(n - 1)]
    cnt = [[] for i in range(n + 1)]
    pc = [0] * (n + 1)
    max_c = 0
    ans = [[0] * (n + 1) for i in range(n + 1)]
    for i in range(n - 1):
        cnt[ab[i][0]].append(ab[i][1])
    for i in range(1, n + 1):
        c = 1
        for ni in cnt[i]:
            if pc[i] != c:
                max_c = max(max_c, c)
                ans[i][ni] = c
                pc[ni] = c
                c += 1
            else:
                c += 1
                max_c = max(max_c, c)
                ans[i][ni] = c
                pc[ni] = c
                c += 1
    print(max_c)
    for i in range(n - 1):
        print(ans[ab[i][0]][ab[i][1]])
    return


# E
def E():
    return


# F
def F():
    return


# Unittest
def resolve():
    D()

    return


# Solve
if __name__ == "__main__":
    D()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

e = []

for i in range((n-1)):
  tmp = input().split(" ")
  e.append([int(tmp[0]), int(tmp[1])])
  
nnum = []

for i in range(n):
  nnum.append(len([j for j in range(n-1) if (i+1) in e[j]]))
  
print(max(nnum)) # 1行目

res = [0 for i in range(n-1)]

for i in range(n): # node i+1について
  x = [j for j in range(n-1) if e[j][1] == i+1] # 親はあるか？
  if len(x) == 0:
    oya = 0
  else:
    oya = res[x[0]]
  
  y = [j for j in range(n-1) if e[j][0] == i+1] # 子の一覧
  if len(y) == 0:
    pass
  else:
    cand = list(range(1, max(nnum)+1))
    cand = [j for j in cand if j != oya]
    for k in range(len(y)):
      res[y[k]] = cand[k]

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
input = sys.stdin.readline
N = int(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

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter,defaultdict,deque
import sys
import bisect
import math
import itertools
import string
import queue
import copy
# import numpy as np
# import scipy
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

def inp(): # n=1
    return int(input())
def inpm(): # x=1,y=2
    return map(int,input().split())
def inpl(): # a=[1,2,3,4,5,...,n]
    return list(map(int, input().split()))
def inpls(): # a=['1','2','3',...,'n']
    return list(input().split())
def inplm(n): # x=[] 複数行
    return list(int(input()) for _ in range(n))
def inpll(n): # [[1,1,1,1],[2,2,2,2],[3,3,3,3]]
    return sorted([list(map(int, input().split())) for _ in range(n)])
def graph():
    n=inp()
    g=[[] for _ in range(n)]
    for i in range(n-1):
        a,b=inpm()
        a-=1
        b-=1
        g[a].append((b,i))
        g[b].append((a,i))
    return n,g
    
def main():
    n,g=graph()
    check = [False for _ in range(n)]
    color=[[] for _ in range(n)]
    ans=[0 for _ in range(n-1)]
    que=[]
    que.append(0)
    while len(que)>0:
        x = que.pop(0)
        check[x]=True
        for i in range(len(g[x])):
            if check[g[x][i][0]]:
                continue
            else:
                que.append(g[x][i][0])
                for j in range(1,n+1):
                    if j not in color[x]:
                        ans[g[x][i][1]]=j
                        color[x].append(j)
                        color[g[x][i][0]].append(j)
                        break
    print(max(ans))
    for i in range(len(ans)):
        print(ans[i])


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

N = int(input())
edge = [list(map(int,input().split())) for i in range(N-1)]

graph = [[] for i in range(N)]
for e in edge:
    graph[e[0]-1].append(e[1]-1)
    graph[e[1]-1].append(e[0]-1)

K = 0
for g in graph:
    K = max(K,len(g))
print(K)

color = [[] for i in range(N)]
L = []
i = 0
for e in edge:
    while True:
        if i%K not in color[e[0]-1] and i%K not in color[e[1]-1]:
            L.append(i%K)
            color[e[0]-1].append(i%K)
            color[e[1]-1].append(i%K)
            break
        i += 1


for l in L:
    print(l+1)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
graph={i+1:[] for i in range(N)}
coloured=[0 for i in range(N+1)]
#↑0から始まってる（ただしkeyはそのまま使える）
count=[]
node_list=[]

for i in range(N-1):
    node=tuple([int(thing) for thing in input().split(" ")])
    a=node[0]
    b=node[1]
    graph[a].append((b,i))
    graph[b].append((a,i))
ranking=sorted(range(1,N),key=lambda x:len(graph[x]),reverse=True)

c_num=len(graph[ranking[0]])

ret=["" for i in range(N-1)]
def what_colour(a_bit,b_bit):
    i=0
    while True:
        if (2**i&a_bit!=0) or (2**i&b_bit!=0):
            i=i+1
            continue
        else:return i


for i in ranking:
    for thing in graph[i]:
        j=thing[0]
        num=thing[1]

        c=what_colour(coloured[i],coloured[j])
        coloured[i]=coloured[i]+2**c
        coloured[j]=coloured[j]+2**c

        graph[j].remove((i,num))
        ret[num]=c
print(c_num)
for thing in ret:
    print(thing+1)

    #処理したらgraphから消してcolourdにビットで（2**色）を加算。処理する前にビット積（&が0になるか確かめる）

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(4100000)
N = int(input())
tree = [[] for _ in range(N+1) ]
already_make = [-1]*(N+1)
for i in range(1,N):
    a,b = 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(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
        for i in range(1,length):
            if bfs_use_coler[val[0]][i] == 1 or bfs_use_coler[n][i] == 1:
                continue
            else:
                use_coloer = i
                break
        if use_coloer == -1:
            last_color +=1
            use_coloer = last_color
        bfs_use_coler[val[0]][use_coloer] = 1
        bfs_use_coler[n][use_coloer] = 1
        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)

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
for i in range(N):
    leni = len(graph[i])
    maxi = max(leni, maxi)
K = maxi
color = [0 for i in range(N-1)]
for i in range(N):
    v = graph[i]
    colk = [False for nnn in range(K)]
    NN = []
    for j in v:
        if i < j:
            n = str(i) + '-' + str(j)
        else:
            n = str(j) + '-' + str(i)
        NN.append(n)
    for s in NN:
        if color[basho[s]] != 0:
            colk[color[basho[s]] - 1] = True
    for s in NN:
        if color[basho[s]] == 0:
            ind = colk.index(False)
            color[basho[s]] = ind + 1
            colk[ind] = True

print(K)
for i in range(N-1):
    print(color[i])

Submission status: Time Limit Exceeded

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)
 
stack = [(0, -1)]
visited = [-1]*n
 
k = 0
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 child_color == -1:
            if tmp == color:
                tmp += 1
            graph[node][i] = (child, 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: Time Limit Exceeded

Solution code:
N = int(input())
E = [tuple(map(lambda x:int(x)-1, input().split())) for _ in range(N-1)]
K = 0
E_sorted = sorted(E, key=lambda x:x[0])
ans = {}
V = [[] for _ in range(N)]
for e in E_sorted:
  a, b = e
  c = 1
  req_K = True
  for i in range(1, K+1):
    if not (i in V[a]):
      c = i
      req_K = False
      break
  if req_K:
    K += 1
    c = K
  V[a].append(c)
  V[a] = list(set(V[a]))
  V[b].append(c)
  V[b] = list(set(V[b]))
  ans[e] = c
print(K)
for e in E:
  print(ans[e])

Submission status: Time Limit Exceeded

Solution code:
import collections

N = int(input())
ab = [list(map(int, input().split())) for _ in range(N-1)]
a = []
b = []
for i in range(N-1):
    a.append(ab[i][0])
for i in range(N-1):
    b.append(ab[i][1])
    
ab_max = []
for i in range(N-1):
    ab_max.append(a[i])
    ab_max.append(b[i])
c = collections.Counter(ab_max)    
    
ans = max(c.values())

print(ans)

l = [i for i in range(1, N+1)]

ndic = {}
for i in range(1, N+1):
    ndic[i] = []

for i in range(N-1):
    a_and_b = list(set(l) ^ (set(ndic[a[i]]).union(set(ndic[b[i]]))))
    p = a_and_b[0]
    print(p)
    ndic[a[i]].append(p)
    ndic[b[i]].append(p)