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:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
from heapq import heappop, heappush
from collections import defaultdict
sys.setrecursionlimit(10**7)
import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal
#from numba import jit

INF = 1 << 50
EPS = 1e-8
mod = 10 ** 9 + 7

def mapline(t = int):
    return map(t, sysread().split())
def mapread(t = int):
    return map(t, read().split())

def dfs(c, to, cols, max_counts, pre_col = 0):
    colors = set()
    colors.add(pre_col)
    for idx, n in to[c]:
        if cols[idx]:continue
        num = 1
        for i in range(num, max_counts+1):
            if not i in colors:
                num = i
                cols[idx] = i
                colors.add(i)
                dfs(n, to, cols, max_counts, i)
                break


def run():
    N = int(sysread())
    to = [[] for _ in range(N+1)]
    cols = [0] * (N-1)
    counts = [0 for i in range(N+1)]
    for i in range(N-1):
        a,b = mapline()
        to[a].append((i, b))
        to[b].append((i, a))
        counts[a] += 1
        counts[b] += 1

    max_counts = max(counts)
    print(max_counts)
    dfs(1, to, cols, max_counts)

    for c in cols:
        print(c)

    #print(a ^ b)
if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
from heapq import heappop, heappush
from collections import defaultdict
sys.setrecursionlimit(10**7)
import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal
#from numba import jit

INF = 1 << 50
EPS = 1e-8
mod = 10 ** 9 + 7

def mapline(t = int):
    return map(t, sysread().split())
def mapread(t = int):
    return map(t, read().split())

def dfs(c, to, cols, max_counts, pre_col = 0):
    colors = set()
    colors.add(pre_col)
    for idx, n in to[c]:
        if cols[idx]:continue
        for i in range(1, max_counts+1):
            if not i in colors:
                cols[idx] = i
                colors.add(i)
                dfs(n, to, cols, max_counts, i)
                break


def run():
    N = int(sysread())
    to = [[] for _ in range(N+1)]
    cols = [0] * (N-1)
    counts = [0 for i in range(N+1)]
    for i in range(N-1):
        a,b = mapline()
        to[a].append((i, b))
        to[b].append((i, a))
        counts[a] += 1
        counts[b] += 1

    max_counts = max(counts)
    print(max_counts)
    dfs(1, to, cols, max_counts)

    for c in cols:
        print(c)




    #print(a ^ b)
if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
import sys
from sys import exit
from collections import deque
from copy import deepcopy
from bisect import bisect_left, bisect_right, insort_left, insort_right
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod=MOD):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
    def list(self):
        l = []
        for k in self:
            l.extend([k]*self[k])
        return l
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]
def pf(x,mode='counter'):
    C = counter()
    p = 2
    while x>1:
        k = 0
        while x%p==0:
            x //= p
            k += 1
        if k>0:
            C.add(p,k)
        p = p+2-(p==2) if p*p<x else x
    if mode=='counter':
        return C
    S = set([1])
    for k in C:
        T = deepcopy(S)
        for x in T:
            for i in range(1,C[k]+1):
                S.add(x*(k**i))
    if mode=='set':
        return S
    if mode=='list':
        return sorted(list(S))

######################################################

N=intput()
node=[list() for _ in range(N+1)]
done=[False]*(N+1)
c=[set() for _ in range(N+1)]
ans=[0]*(N-1)
S=dict()
for i in range(N-1):
    u,v=mint()
    node[u].append(v)
    node[v].append(u)
    S[(u,v)]=i
    S[(v,u)]=i
K=max(node,key=len)
print(len(K))
if K==N-1:
    lprint(list(range(1,N)))
    exit()
q=deque([1])
done[1]=True
while q:
    u=q.popleft()
    for v in node[u]:
        if not done[v]:
            i=1
            while i in c[u] or i in c[v]:
                i+=1
            c[u].add(i)
            c[v].add(i)
            ans[S[(u,v)]]=i
            done[v]=True
            q.append(v)
#print(max(ans))
lprint(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from sys import exit
from collections import deque
from copy import deepcopy
from bisect import bisect_left, bisect_right, insort_left, insort_right
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod=MOD):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
    def list(self):
        l = []
        for k in self:
            l.extend([k]*self[k])
        return l
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]
def pf(x,mode='counter'):
    C = counter()
    p = 2
    while x>1:
        k = 0
        while x%p==0:
            x //= p
            k += 1
        if k>0:
            C.add(p,k)
        p = p+2-(p==2) if p*p<x else x
    if mode=='counter':
        return C
    S = set([1])
    for k in C:
        T = deepcopy(S)
        for x in T:
            for i in range(1,C[k]+1):
                S.add(x*(k**i))
    if mode=='set':
        return S
    if mode=='list':
        return sorted(list(S))

######################################################

N=intput()
node=[list() for _ in range(N+1)]
done=[False]*(N+1)
c=[set() for _ in range(N+1)]
ans=[0]*(N-1)
S=dict()
for i in range(N-1):
    u,v=mint()
    node[u].append(v)
    node[v].append(u)
    S[(u,v)]=i
    S[(v,u)]=i
q=deque([1])
done[1]=True
while q:
    u=q.popleft()
    for v in node[u]:
        if not done[v]:
            i=1
            while i in c[u] or i in c[v]:
                i+=1
            c[u].add(i)
            c[v].add(i)
            ans[S[(u,v)]]=i
            done[v]=True
            q.append(v)
print(max(ans))
lprint(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
ab = [list(map(int, input().split())) for _ in range(n-1)]

c = [[] for _ in range(n)]
for a, b in ab:
    a, b = a-1, b-1
    c[a].append(b)
    c[b].append(a)

s = 0
for i in range(n):
    if len(c[i]) > s:
        s = i

e = [0] * n
l = [[0] * n for _ in range(n)]
q = deque()
q.append((s, 0))
while q:
    f, v = q.pop()
    e[f] = 1
    j = 1
    for i in c[f]:
        if e[i] == 0:
            if j == v:
                j += 1
            q.appendleft((i, j))
            l[min(f, i)][max(f, i)] = j
            j += 1

ans = []
for a, b in ab:
    a, b = a-1, b-1
    ans.append(l[a][b])

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
ab = [list(map(int, input().split())) for _ in range(n-1)]

c = [[] for _ in range(n)]
for a, b in ab:
    a, b = a-1, b-1
    c[a].append(b)
    c[b].append(a)

s = 0
for i in range(n):
    if len(c[i]) > s:
        s = i

e = [0] * n
l = [0] * (n-1)
q = deque()
q.append((s, 0))
while q:
    f, v = q.pop()
    e[f] = 1
    j = 1
    for i in c[f]:
        if e[i] == 0:
            if j == v:
                j += 1
            q.appendleft((i, j))
            l[ab.index([min(f, i)+1, max(f, i)+1])] = j
            j += 1

print(max(l))
for i in l:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
if __name__ == "__main__":
    import sys
    from collections import deque
    input = sys.stdin.readline
    N = int(input())
    edges = [[] for _ in range(N)]
    for i in range(N-1):
        a,b = map(int,input().split())
        a -= 1
        b -= 1
        edges[a].append((b,i))
        edges[b].append((a,i))

    color = [None]*(N-1)
    SIZE = 1
    q = deque([(0,None)])
    while q:
        v, prev_color = q.popleft()
        colors = list(range(1,SIZE+1))
        if prev_color:
            colors.remove(prev_color)
        for w, i in edges[v]:
            if not color[i]:
                if colors:
                    color[i] = colors.pop(0)
                else:
                    SIZE += 1
                    color[i] = SIZE
                q.append((w,color[i]))
    print(SIZE)
    for n in range(N-1):
        print(color[n])

Submission status: Time Limit Exceeded

Solution code:
if __name__ == "__main__":
    from collections import deque
    N = int(input())
    edges = [[] for _ in range(N)]
    for i in range(N-1):
        a,b = map(int,input().split())
        a -= 1
        b -= 1
        edges[a].append((b,i))
        edges[b].append((a,i))

    color = [None]*(N-1)
    SIZE = 1
    q = deque([(0,None)])
    while q:
        v, prev_color = q.popleft()
        colors = list(range(1,SIZE+1))
        if prev_color:
            colors.remove(prev_color)
        for w, i in edges[v]:
            if not color[i]:
                if colors:
                    color[i] = colors.pop(0)
                else:
                    SIZE += 1
                    color[i] = SIZE
                q.append((w,color[i]))
    print(SIZE)
    for n in range(N-1):
        print(color[n])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N = int(input())
edges = [[] for _ in range(N)]
for i in range(N-1):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    edges[a].append((b,i))
    edges[b].append((a,i))

color = [None]*(N-1)
SIZE = 1
q = deque([(0,None)])
while q:
    v, prev_color = q.popleft()
    colors = list(range(1,SIZE+1))
    if prev_color:
        colors.remove(prev_color)
    for w, i in edges[v]:
        if not color[i]:
            if colors:
                color[i] = colors.pop(0)
            else:
                SIZE += 1
                color[i] = SIZE
            q.append((w,color[i]))
print(SIZE)
for n in range(N-1):
    print(color[n])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())

conn = [[] for _ in range(N + 1)]
e = {}
for i in range(1, N):
    a, b = [int(x) for x in input().split()]
    conn[a].append(b)
    conn[b].append(a)
    if a < b:
        e[(a, b)] = i
    else:
        e[(b, a)] = i

K = max(len(x) for x in conn)
v0 = 0
for i in range(N + 1):
    if len(conn[i]) == K:
        v0 = i
        break

q = deque([v0])
ans = [None] * N
available = [[i for i in range(1, K + 1)] for _ in range(N + 1)]
check = [False] * (N + 1)
check[v0] = True
while q:
    v = q.popleft()
    for w in conn[v]:
        if check[w] == False:
            check[w] = True
            q.append(w)
            c = available[v][0]
            available[v].remove(c)
            available[w].remove(c)
            if v < w:
                ans[e[(v, w)]] = c
            else:
                ans[e[(w, v)]] = c

print(K)
for i in range(1, N):
    print(ans[i])

Submission status: Time Limit Exceeded

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


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


def MI(): return map(int, sys.stdin.readline().split())


def LI(): return list(map(int, sys.stdin.readline().split()))


def main():
    N = II()
    graph = [[] for i in range(N)]
    prev = [-1 for i in range(N)]
    colors = {}
    edges = []
    for _ in range(N-1):
        a, b = MI()
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
        edges.append([a-1, b-1])
    max_edge = 0
    max_edge_idx = -1
    for i in range(len(graph)):
        length = len(graph[i])
        if length >= max_edge:
            max_edge = length
            max_edge_idx = i

    deque = cl.deque([max_edge_idx])
    unused_colors_tmp = set(list(range(1, max_edge+1)))
    while len(deque) > 0:
        target = deque.popleft()
        pre = prev[target]
        unused_colors = set(unused_colors_tmp)
        pre_key = (target, pre) if target < pre else (pre, target)
        if pre != -1:
            unused_colors.remove(colors[pre_key])

        connecteds = graph[target]
        color = 1
        for connected in connecteds:
            key = (target, connected) if target < connected else (
                connected, target)
            if key in colors:
                unused_colors.discard(colors[key])
                continue

            while not color in unused_colors:
                color += 1
            colors[key] = color
            prev[connected] = target
            deque.append(connected)
            unused_colors.remove(color)

    print(max_edge)

    for edge in edges:
        print(colors[(edge[0], edge[1])])


main()

Submission status: Time Limit Exceeded

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


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


def MI(): return map(int, sys.stdin.readline().split())


def LI(): return list(map(int, sys.stdin.readline().split()))


def main():
    N = II()
    graph = [[] for i in range(N)]
    prev = [-1 for i in range(N)]
    colors = {}
    edges = []
    for _ in range(N-1):
        a, b = MI()
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
        edges.append([a-1, b-1])
    max_edge = 0
    max_edge_idx = -1
    for i in range(len(graph)):
        length = len(graph[i])
        if length >= max_edge:
            max_edge = length
            max_edge_idx = i

    deque = cl.deque([max_edge_idx])
    unused_colors_tmp = set(list(range(1, max_edge+1)))
    while len(deque) > 0:
        target = deque.popleft()
        pre = prev[target]
        unused_colors = set(unused_colors_tmp)
        pre_key = (target, pre) if target < pre else (pre, target)
        if pre != -1:
            unused_colors.remove(colors[pre_key])

        connecteds = graph[target]

        for connected in connecteds:
            key = (target, connected) if target < connected else (
                connected, target)
            if key in colors:
                unused_colors.discard(colors[key])
                continue

            color = min(unused_colors)
            colors[key] = color
            prev[connected] = target
            deque.append(connected)
            unused_colors.remove(color)

    print(max_edge)

    for edge in edges:
        print(colors[(edge[0], edge[1])])


main()

Submission status: Time Limit Exceeded

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


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


def MI(): return map(int, sys.stdin.readline().split())


def LI(): return list(map(int, sys.stdin.readline().split()))


def main():
    N = II()
    graph = [[] for i in range(N)]
    prev = [-1 for i in range(N)]
    colors = {}
    edges = []
    for _ in range(N-1):
        a, b = MI()
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
        edges.append([a-1, b-1])
    max_edge = 0
    max_edge_idx = -1
    for i in range(len(graph)):
        length = len(graph[i])
        if length >= max_edge:
            max_edge = length
            max_edge_idx = i

    deque = cl.deque([max_edge_idx])
    while len(deque) > 0:
        target = deque.popleft()
        pre = prev[target]
        unused_colors = set(list(range(1, max_edge+1)))
        pre_key = (target, pre) if target < pre else (pre, target)
        if pre != -1:
            unused_colors.remove(colors[pre_key])

        connecteds = graph[target]

        for connected in connecteds:
            key = (target, connected) if target < connected else (
                connected, target)
            if key in colors:
                unused_colors.discard(colors[key])
                continue

            color = min(unused_colors)
            colors[key] = color
            prev[connected] = target
            deque.append(connected)
            unused_colors.remove(color)

    print(max_edge)

    for edge in edges:
        print(colors[(edge[0], edge[1])])


main()

Submission status: Time Limit Exceeded

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


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


def MI(): return map(int, sys.stdin.readline().split())


def LI(): return list(map(int, sys.stdin.readline().split()))


def main():
    N = II()
    graph = [[] for i in range(N)]
    prev = [-1 for i in range(N)]
    colors = {}
    edges = []
    for _ in range(N-1):
        a, b = MI()
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
        edges.append([a-1, b-1])
    max_edge = 0
    max_edge_idx = -1
    for i in range(len(graph)):
        length = len(graph[i])
        if length >= max_edge:
            max_edge = length
            max_edge_idx = i

    deque = cl.deque([max_edge_idx])
    while len(deque) > 0:
        target = deque.popleft()
        pre = prev[target]
        unused_colors = set(list(range(1, max_edge+1)))
        if pre != -1:
            unused_colors.remove(colors[(target, pre)])

        connecteds = graph[target]

        for connected in connecteds:
            if (target, connected) in colors:
                unused_colors.discard(colors[(connected, target)])
                continue

            color = min(unused_colors)
            colors[(target, connected)] = color
            colors[(connected, target)] = color
            prev[connected] = target
            deque.append(connected)
            unused_colors.remove(color)

    print(max_edge)

    for edge in edges:
        print(colors[(edge[0], edge[1])])


main()

Submission status: Time Limit Exceeded

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


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


def MI(): return map(int, sys.stdin.readline().split())


def LI(): return list(map(int, sys.stdin.readline().split()))


def main():
    N = II()
    graph = [[] for i in range(N)]
    colors = [[-1 for j in range(N)] for i in range(N)]
    prev = [-1 for i in range(N)]
    edges = []
    for _ in range(N-1):
        a, b = MI()
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
        edges.append([a-1, b-1])
    max_edge = 0
    max_edge_idx = -1
    for i in range(len(graph)):
        length = len(graph[i])
        if length >= max_edge:
            max_edge = length
            max_edge_idx = i

    deque = cl.deque([max_edge_idx])
    while len(deque) > 0:
        target = deque.popleft()
        pre = prev[target]
        unused_colors = set(list(range(1, max_edge+1)))
        if pre != -1:
            unused_colors.remove(colors[target][pre])

        connecteds = graph[target]

        for connected in connecteds:
            if colors[target][connected] != -1:
                unused_colors.discard(colors[connected][target])
                continue

            color = min(unused_colors)
            colors[target][connected] = color
            colors[connected][target] = color
            prev[connected] = target
            deque.append(connected)
            unused_colors.remove(color)

    print(max_edge)

    for edge in edges:
        print(colors[edge[0]][edge[1]])


main()

Submission status: Time Limit Exceeded

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


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


def MI(): return map(int, sys.stdin.readline().split())


def LI(): return list(map(int, sys.stdin.readline().split()))


def main():
    N = II()
    graph = [[] for i in range(N)]
    colors = [[-1 for j in range(N)] for i in range(N)]
    prev = [-1 for i in range(N)]
    edges = []
    for _ in range(N-1):
        a, b = MI()
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
        edges.append([a-1, b-1])
    max_edge = 0
    max_edge_idx = -1
    for i in range(len(graph)):
        length = len(graph[i])
        if length >= max_edge:
            max_edge = length
            max_edge_idx = i

    deque = cl.deque([max_edge_idx])
    while len(deque) > 0:
        target = deque.popleft()
        pre = prev[target]
        used_colors = set([])
        if pre != -1:
            used_colors.add(colors[pre][target])

        connecteds = graph[target]

        color = 1
        for connected in connecteds:
            if colors[target][connected] != -1:
                used_colors.add(colors[target][connected])
                continue

            while color in used_colors:
                color += 1

            colors[target][connected] = color
            colors[connected][target] = color
            prev[connected] = target
            deque.append(connected)
            used_colors.add(color)

    print(max_edge)

    for edge in edges:
        print(colors[edge[0]][edge[1]])


main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def BFS(tree):
    color_used = [set() for _ in range(N)]
    v_dist = [-1]*N

    queue = deque([0])
    v_dist[0] = 0

    while queue:
        v = queue.popleft()
        
        for n_v in tree[v]:
            if v_dist[n_v] < 0:
                v_dist[n_v] = v_dist[v] + 1
                if colors - color_used[v] == set():
                    c_max = max(colors)
                    colors.add(c_max+1)
                    color_used[v].add(c_max+1)
                    color_used[n_v].add(c_max+1)
                    coloring[v][n_v] = c_max + 1
                else:
                    d_color = (colors - color_used[v]).pop()
                    coloring[v][n_v] = d_color
                    color_used[v].add(d_color)
                    color_used[n_v].add(d_color)
                queue.append(n_v)

N = int(input())
tree = [[] for i in range(N)]
edges = []

for i in range(N - 1):
    edges.append(tuple(map(int, input().split())))
    tree[edges[-1][0] - 1].append(edges[-1][1] - 1)
    tree[edges[-1][1] - 1].append(edges[-1][0] - 1)

coloring = [[0]*N for _ in range(N)]
colors = set([1])

BFS(tree)

print(len(colors))

for edge in edges:
    print(coloring[edge[0] - 1][edge[1] - 1])

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict
sys.setrecursionlimit(10**8)

N = int(input())
graph = [[] for _ in range(N)]
numOfEdges = [0 for _ in range(N)]
visited = [0 for _ in range(N)]
color = [[-1 for _ in range(N)] for _ in range(N)]
edges = defaultdict(int)

for i in range(1, N):
    a, b = map(int, input().split())
    a -= 1; b -= 1;
    numOfEdges[a] += 1
    numOfEdges[b] += 1
    edges[(a, b)] = 0
    graph[a].append(b)
    graph[b].append(a)

def dfs(prev, now, col):
    if visited[now]:
        return
    visited[now] = 1
    i = 1
    for adj in graph[now]:
        if adj == prev:
            continue
        if now < adj:
            edges[(now, adj)] = col + i
        else:
            edges[(adj, now)] = col + i
        dfs(now, adj, col+i)
        i += 1

dfs(-1, 0, 1)
maxColor = max(numOfEdges)
print(maxColor)

for k, i in edges.items():
    e = i % maxColor
    if e:
        print(e)
    else:
        print(maxColor)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**8)

N = int(input())
graph = [[] for _ in range(N)]
numOfEdges = [0 for _ in range(N)]
visited = [0 for _ in range(N)]
color = [[-1 for _ in range(N)] for _ in range(N)]
edges = []

for i in range(1, N):
    a, b = map(int, input().split())
    a -= 1; b -= 1;
    edges.append((a, b))
    numOfEdges[a] += 1
    numOfEdges[b] += 1
    graph[a].append(b)
    graph[b].append(a)

def dfs(prev, now, col):
    if visited[now]:
        return
    visited[now] = 1
    i = 1
    for adj in graph[now]:
        if adj == prev:
            continue
        color[now][adj] = col + i
        color[adj][now] = col + i
        dfs(now, adj, col+i)
        i += 1

dfs(-1, 0, 1)
maxColor = max(numOfEdges)
print(maxColor)

for e in edges:
    a, b = e
    c = color[a][b] % maxColor
    if c == 0:
        print(maxColor)
    else:
        print(c)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**8)

N = int(input())
graph = [[] for _ in range(N)]
numOfEdges = [0 for _ in range(N)]
visited = [0 for _ in range(N)]
color = [[-1 for _ in range(N)] for _ in range(N)]
edges = []

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

def dfs(prev, now, col):
    if visited[now]:
        return
    visited[now] = 1
    numOfEdges[now] = len(graph[now])
    i = 1
    for adj in graph[now]:
        if adj == prev:
            continue
        color[now][adj] = col + i
        color[adj][now] = col + i
        dfs(now, adj, col+i)
        i += 1

dfs(-1, 0, 1)
maxColor = max(numOfEdges)
print(maxColor)

for e in edges:
    a, b = e
    c = color[a][b] % maxColor
    if c == 0:
        print(maxColor)
    else:
        print(c)

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(100000)

class Tree():
    def __init__(self, n, root, connects):
        self.root = root
        self.connects = connects
        self.parents = [0] * n
        self.parents[root] = None
        self.children = [0] * n
        self.children[self.root] = connects[self.root]
        self.make_tree(self.root)

    def make_tree(self, node):
        for child in self.children[node]:
            self.parents[child] = node
            self.children[child] = [c for c in self.connects[child] if c != node]
            if self.children[child] != []:
                self.make_tree(child)


def main():
    n = int(input())
    G = [[] for _ in range(n)]
    ID = [dict() for _ in range(n)]
    for i in range(n - 1):
        a, b = map(lambda x: int(x) - 1, input().split())
        G[a].append(b)
        G[b].append(a)
        ID[a][b] = i
        ID[b][a] = i
    t = Tree(n, root = 0, connects = G)
    m = max(len(g) for g in G)
    ans = [0] * (n - 1)
    def bfs(a, pre = set()):
        color = list(set(range(m)) - pre)
        for b in t.children[a]:
            c = color.pop()
            ans[ID[a][b]] = c + 1
            bfs(b, set([c]))
    bfs(0)
    print(m)
    [print(a) for a in ans]
      
if __name__ == '__main__':
    main()