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:
from collections import deque
import sys
input = sys.stdin.readline
    
def bfs(v, N, G, E):
    visited = [0]*N
    queue = deque()
    new_color = 1
    used_color = set()
    num_used_color = 0
    node2colors = [set() for _ in range(N)]
    queue.append(v)
    visited[v] = 1
    while queue:
        q = queue.popleft()
        # print("q",q)
        num_color_from_q = 0
        while G[q]:
            nex = G[q].popleft()
            if visited[nex]:
                continue
            visited[nex] = 1
            rest = num_used_color - num_color_from_q
            # print(rest)
            if rest > 0:
                usd_c = used_color - node2colors[q]
                if usd_c:
                    # print(used_color, node2colors[q])
                    usd_c = min(usd_c)
                    E[(q, nex)][1] = usd_c
                    node2colors[q].add(usd_c)
                    num_color_from_q += 1
                    node2colors[nex].add(usd_c)
                else:
                    # print(num_used_color, num_color_from_q)
                    new_c = new_color
                    new_color += 1
                    num_used_color += 1
                    E[(q, nex)][1] = new_c
                    node2colors[q].add(new_c)
                    num_color_from_q += 1
                    node2colors[nex].add(new_c)
                    used_color.add(new_c)
                    
            else:
                new_c = new_color
                new_color += 1
                num_used_color += 1
                E[(q, nex)][1] = new_c
                node2colors[q].add(new_c)
                num_color_from_q += 1
                node2colors[nex].add(new_c)
                used_color.add(new_c)
        
            queue.append(nex)
    return num_used_color

def main():
    N = int(input())
    G = [deque() for _ in range(N)]
    E = dict() # (a, b) -> [idx, color]
    for i in range(N-1):
        a, b = map(lambda x: int(x)-1, input().split())
        G[a].append(b)
        G[b].append(a)
        E[(a, b)] = [i, 0]
    K = bfs(0, N, G, E)
    # ans_list = [value for value in E.values()]
    print(K)
    for value in E.values():
        print(value[1])
main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline
    
def bfs(v, N, G, E):
    queue = deque()
    new_color = 1
    used_color = set()
    num_used_color = 0
    node2colors = [set() for _ in range(N)]
    queue.append(v)
    while queue:
        q = queue.popleft()
        # print("q",q)
        num_color_from_q = 0
        while G[q]:
            nex = G[q].popleft()
            rest = num_used_color - num_color_from_q
            # print(rest)
            if rest > 0:
                usd_c = used_color - node2colors[q]
                if usd_c:
                    # print(used_color, node2colors[q])
                    usd_c = min(usd_c)
                    E[(q, nex)][1] = usd_c
                    node2colors[q].add(usd_c)
                    num_color_from_q += 1
                    node2colors[nex].add(usd_c)
                else:
                    # print(num_used_color, num_color_from_q)
                    new_c = new_color
                    new_color += 1
                    num_used_color += 1
                    E[(q, nex)][1] = new_c
                    node2colors[q].add(new_c)
                    num_color_from_q += 1
                    node2colors[nex].add(new_c)
                    used_color.add(new_c)
                    
            else:
                new_c = new_color
                new_color += 1
                num_used_color += 1
                E[(q, nex)][1] = new_c
                node2colors[q].add(new_c)
                num_color_from_q += 1
                node2colors[nex].add(new_c)
                used_color.add(new_c)
        
            queue.append(nex)
    return num_used_color

def main():
    N = int(input())
    G = [deque() for _ in range(N)]
    E = dict() # (a, b) -> [idx, color]
    for i in range(N-1):
        a, b = map(lambda x: int(x)-1, input().split())
        G[a].append(b)
        E[(a, b)] = [i, 0]
    K = bfs(0, N, G, E)
    # ans_list = [value for value in E.values()]
    print(K)
    for value in E.values():
        print(value[1])
main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline
    
def bfs(v, N, G, E):
    K = 0
    queue = deque()
    new_color = 1
    used_color = set()
    node2colors = [set() for _ in range(N)]
    queue.append(v)
    while queue:
        q = queue.popleft()
        while G[q]:
            nex = G[q].popleft()
            dif = used_color - node2colors[q]
            if dif:
                usd_c = dif.pop()
                dif.add(usd_c)
                E[(q, nex)][1] = usd_c
                node2colors[q].add(usd_c)
                node2colors[nex].add(usd_c)
            else:
                new_c = new_color
                new_color += 1
                E[(q, nex)][1] = new_c
                node2colors[q].add(new_c)
                node2colors[nex].add(new_c)
                used_color.add(new_c)
                K += 1
            queue.append(nex)
    return K

def main():
    N = int(input())
    G = [deque() for _ in range(N)]
    E = dict() # (a, b) -> [idx, color]
    for i in range(N-1):
        a, b = map(lambda x: int(x)-1, input().split())
        G[a].append(b)
        E[(a, b)] = [i, 0]
    K = bfs(0, N, G, E)
    # ans_list = [value for value in E.values()]
    print(K)
    for value in E.values():
        print(value[1])
main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
G = [deque() for _ in range(N)]
E = dict() # (a, b) -> [idx, color]
for i in range(N-1):
    a, b = map(lambda x: int(x)-1, input().split())
    G[a].append(b)
    E[(a, b)] = [i, 0]
    

K = 0
new_color = [i for i in range(N-1, 0, -1)]
used_color = set()
queue = deque()
node2colors = [set() for _ in range(N)]
def bfs(v):
    global K
    # seen[v] = 1
    queue.append(v)
    while queue:
        q = queue.popleft()
        # if seen[q]:
            # continue
        while G[q]:
            nex = G[q].popleft()
            dif = used_color.difference(node2colors[q])
            if dif:
                usd_c = dif.pop()
                dif.add(usd_c)
                E[(q, nex)][1] = usd_c
                node2colors[q].add(usd_c)
                node2colors[nex].add(usd_c)
            else:
                new_c = new_color.pop()
                E[(q, nex)][1] = new_c
                node2colors[q].add(new_c)
                node2colors[nex].add(new_c)
                used_color.add(new_c)
                K += 1
            queue.append(nex)

bfs(0)
ans_list = [value for value in E.values()]
print(K)
for i in range(N-1):
    print(ans_list[i][1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
G = [deque() for _ in range(N)]
E = dict() # (a, b) -> [idx, color]
for i in range(N-1):
    a, b = map(lambda x: int(x)-1, input().split())
    G[a].append(b)
    E[(a, b)] = [i, 0]
    

K = 0
new_color = [i for i in range(N-1, 0, -1)]
used_color = set()
queue = deque()
node2colors = [set() for _ in range(N)]
def bfs(v):
    global K
    # seen[v] = 1
    queue.append(v)
    while queue:
        q = queue.popleft()
        # if seen[q]:
            # continue
        for edge in range(len(G[q])):
            nex = G[q][edge]
            dif = used_color.difference(node2colors[q])
            if dif:
                usd_c = dif.pop()
                dif.add(usd_c)
                E[(q, nex)][1] = usd_c
                node2colors[q].add(usd_c)
                node2colors[nex].add(usd_c)
            else:
                new_c = new_color.pop()
                E[(q, nex)][1] = new_c
                node2colors[q].add(new_c)
                node2colors[nex].add(new_c)
                used_color.add(new_c)
                K += 1
            queue.append(nex)

bfs(0)
ans_list = [value for value in E.values()]
ans_list.sort()
print(K)
for i in range(N-1):
    print(ans_list[i][1])

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
ab = []
g = [[] for i in range(n)]
for i in range(n-1):
    a,b = map(int,input().split())
    a-=1
    b-=1
    g[a].append(b)
    g[b].append(a)
    ab.append([a,b])

k = max([len(i) for i in g])
print(k)

reach = [False]*n
c = [[0]*n for i in range(n)]
from collections import deque
q = deque([[0,-1]])
reach[0] = True

while q:
    cur,col = q.popleft()
    for next_i in g[cur]:
        if not reach[next_i]:
            col = (col+1)%k
            c[cur][next_i] = col
            c[next_i][cur] = col
            q.append([next_i,col])
            reach[next_i] = True

for a,b in ab:
    print(c[a][b]+1)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
ab = []
g = [[] for i in range(n)]
for i in range(n-1):
    a,b = map(int,input().split())
    a-=1
    b-=1
    g[a].append(b)
    g[b].append(a)
    ab.append([a,b])

k = max([len(i) for i in g])
print(k)

reach = [False]*n
c = [[0]*n for i in range(n)]
from collections import deque
q = deque([[0,-1]])

while q:
    cur,col = q.popleft()
    reach[cur] = True
    for next_i in g[cur]:
        if not reach[next_i]:
            col = (col+1)%k
            c[cur][next_i] = col
            c[next_i][cur] = col
            q.append([next_i,col])

for a,b in ab:
    print(c[a][b]+1)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
ab = []
g = [[] for i in range(n)]
for i in range(n-1):
    a,b = map(int,input().split())
    a-=1
    b-=1
    g[a].append(b)
    g[b].append(a)
    ab.append([a,b])

k = max([len(i) for i in g])
print(k)

reach = [False]*n
c = [[0]*n for i in range(n)]
from collections import deque
q = deque([[0,-1]])

while q:
    cur,col = q.popleft()
    reach[cur] = True
    for next_i in g[cur]:
        if not reach[next_i]:
            a,b = sorted([cur,next_i])
            col = (col+1)%k
            c[a][b] = col
            q.append([next_i,col])

for a,b in ab:
    print(c[a][b]+1)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

a = []
b = []
g = [[] for i in range(n)]
ans = [0 for i in range(n-1)]
vind = dict()

for i in range(n-1):
    pa,pb = map(int, input().split())
    pa -= 1
    pb -= 1
    a.append(pa)
    b.append(pb)
    g[pa].append(pb)
    g[pb].append(pa)
    vind[f"{pa}_{pb}"] = i
    vind[f"{pb}_{pa}"] = i


for i in range(n):
    
    uc = []
    for j in g[i]:
        ind = vind[f"{i}_{j}"]
        uc.append(ans[ind])
    c=1
    for j in g[i]:
        ind = vind[f"{i}_{j}"]
        if ans[ind] == 0: 
            while c in uc: c+=1
            ans[ind] = c
            uc.append(c)


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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

a = []
b = []
g = [[] for i in range(n)]
ans = [0 for i in range(n-1)]
vind = dict()

for i in range(n-1):
    pa,pb = map(int, input().split())
    pa -= 1
    pb -= 1
    a.append(pa)
    b.append(pb)
    g[pa].append(pb)
    g[pb].append(pa)
    vind[f"{pa}_{pb}"] = i
    vind[f"{pb}_{pa}"] = i


for i in range(n):
    color_use = [False for i in range(n+1)]
    for j in g[i]:
        ind = vind[f"{i}_{j}"]
        if ans[ind] >= 0: color_use[ans[ind]] = True
    color = 1
    for j in g[i]:
        ind = vind[f"{i}_{j}"]
        if ans[ind] == 0:
            while(color_use[color]):
                color += 1
            ans[ind] = color
            color_use[color] = True
print(max(ans))
for i in range(n-1):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
from functools import reduce
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

def bfs(k):
    c = [[0]*n for i in range(n)]
    dist = [-1]*n
    que = deque([0])
    dist[0] = 0
    v_prev = 0
    while que:
        v = que.popleft()
        d = dist[v]
        color = set(range(1, k+1))
        used = []
        for w in g[v]:
            if dist[w] > -1:
                used.append(c[v][w])
        color.difference_update(used)
        color = deque(color)
        for w in g[v]:
            if dist[w] > -1:
                continue
            c[v][w] = c[w][v] = color.popleft()
            dist[w] = d + 1            
            que.append(w)
    return c

n = INT()
a = [0]*(n-1)
b = [0]*(n-1)
g = [[] for i in range(n)]
for i in range(n-1):
    a[i], b[i] = MAP()
    a[i] -= 1
    b[i] -= 1
    g[a[i]].append(b[i])
    g[b[i]].append(a[i])
k = 0
for x in g:
    k = max(k, len(x))
print(k)
c = bfs(k)
for i in range(n-1):
    print(c[a[i]][b[i]])

Submission status: Time Limit Exceeded

Solution code:
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
from functools import reduce
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

def bfs():
    c = [[0]*n for i in range(n)]
    dist = [-1]*n
    que = deque([0])
    dist[0] = 0
    v_prev = 0
    k = 0
    while que:
        v = que.popleft()
        d = dist[v]
        color = set(range(1, n))
        used = []
        for w in g[v]:
            if dist[w] > -1:
                used.append(c[v][w])
        color.difference_update(used)
        color = deque(color)
        for w in g[v]:
            if dist[w] > -1:
                continue
            c[v][w] = c[w][v] = color.popleft()
            k = max(k, c[v][w])
            dist[w] = d + 1            
            que.append(w)
    return k, c

n = INT()
a = [0]*(n-1)
b = [0]*(n-1)
g = [[] for i in range(n)]
for i in range(n-1):
    a[i], b[i] = MAP()
    a[i] -= 1
    b[i] -= 1
    g[a[i]].append(b[i])
    g[b[i]].append(a[i])
k, c = bfs()
print(k)
for i in range(n-1):
    print(c[a[i]][b[i]])

Submission status: Time Limit Exceeded

Solution code:
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
from functools import reduce
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

def bfs():
    c = [[0]*n for i in range(n)]
    dist = [-1]*n
    que = deque([0])
    dist[0] = 0
    v_prev = 0
    k = 0
    while que:
        v = que.popleft()
        d = dist[v]
        color = 1
        used = []
        for w in g[v]:
            if dist[w] > -1:
                used.append(c[v][w])
        for w in g[v]:
            if dist[w] > -1:
                continue
            while color in used:
                color += 1
            c[v][w] = c[w][v] = color
            k = max(k, color)
            dist[w] = d + 1            
            que.append(w)
            color += 1
    return k, c

n = INT()
a = [0]*(n-1)
b = [0]*(n-1)
g = [[] for i in range(n)]
for i in range(n-1):
    a[i], b[i] = MAP()
    a[i] -= 1
    b[i] -= 1
    g[a[i]].append(b[i])
    g[b[i]].append(a[i])
k, c = bfs()
print(k)
for i in range(n-1):
    print(c[a[i]][b[i]])

Submission status: Time Limit Exceeded

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
edges = [[] for _ in range(n)]
ab = [[i] + LI() for i in range(n-1)]
col = [defaultdict(int) for _ in range(n)]
cnt = [0] * n
for i, a, b in ab:
    edges[a-1].append((i, b-1))
    edges[b-1].append((i, a-1))
    cnt[a-1] += 1
    cnt[b-1] += 1

k = max(cnt)
print(k)
used_edge = [False] * n
que = deque([(0, -1)])
edges_color = [None] * (n-1)
while que:
    v, p = que.popleft()
    for i, u in edges[v]:
        if used_edge[i]:
            continue
        if u == p:
            continue
        cnt = 1
        while col[u][cnt] or col[v][cnt]:
            cnt += 1
        col[u][cnt] = 1
        col[v][cnt] = 1
        edges_color[i] = cnt
        used_edge[i] = False
        que.append((u, v))
for c in edges_color:
    print(c)

Submission status: Time Limit Exceeded

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
edges = [[] for _ in range(n)]
ab = [[i] + LI() for i in range(n-1)]
col = [defaultdict(lambda : 0) for _ in range(n)]
cnt = [0] * n
for i, a, b in ab:
    edges[a-1].append((i, b-1))
    edges[b-1].append((i, a-1))
    cnt[a-1] += 1
    cnt[b-1] += 1

k = max(cnt)
print(k)
used_edge = [False] * n
que = deque([(0, -1)])
edges_color = [None] * (n-1)
while que:
    v, p = que.popleft()
    for i, u in edges[v]:
        if used_edge[i]:
            continue
        if u == p:
            continue
        cnt = 1
        while col[u][cnt] or col[v][cnt]:
            cnt += 1
        col[u][cnt] = 1
        col[v][cnt] = 1
        edges_color[i] = cnt
        used_edge[i] = False
        que.append((u, v))
for c in edges_color:
    print(c)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
deg = [0 for _ in range(N)]
edges = [[] for _ in range(N - 1)]
for i in range(N - 1):
    a, b = map(int, input().split())
    edges[i] = [a - 1, b - 1]
    deg[a - 1] += 1
    deg[b - 1] += 1
deg_max = max(deg)

def add(arg):  return 1 + arg % deg_max

ans = [0 for _ in range(N - 1)]
usd = [[0 for _ in range(deg_max + 3)] for _ in range(N)]
temp = 0
for i in range(N - 1):
    temp = add(temp)
    a = edges[i][0]
    b = edges[i][1]
    while(usd[a][temp] == 1 or usd[b][temp] == 1):  add(temp)
    ans[i] = temp
    usd[a][temp] = 1
    usd[b][temp] = 1
print(deg_max)
for i in range(N - 1):  print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
deg = [0 for _ in range(N)]
edges = [[] for _ in range(N - 1)]
for i in range(N - 1):
    a, b = map(int, input().split())
    edges[i] = [a - 1, b - 1]
    deg[a - 1] += 1
    deg[b - 1] += 1
deg_max = max(deg)

def add(arg):  return 1 + arg % deg_max

ans = [0 for _ in range(N - 1)]
usd = [[0 for _ in range(deg_max + 3)] for _ in range(N)]
temp = 0
for i in range(N - 1):
    temp = add(temp)
    a = edges[i][0]
    b = edges[i][1]
    while(usd[a][temp] == 0 and usd[b][temp] == 0):  add(temp)
    ans[i] = temp
    usd[a][temp] = 1
    usd[b][temp] = 1
print(deg_max)
for i in range(N - 1):  print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n=int(input())
tree=[[] for _ in range(n+1)]
for i in range(1,n):
  a,b=map(int,input().split())
  tree[a].append([b,i])
  tree[b].append([a,i])
queue=deque([[1,1]])
ans=[-1]*(n+1)

while queue:
  v,i=queue.popleft()
  color=1
  for nv,j in tree[v]:
    if ans[i]==color:
      color+=1
    if not ans[nv]==-1:
      continue
    queue.append([nv,color])
    ans[j]=color
    color+=1
print(max(ans))
for i in range(1,n):
  print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
import collections

n = int(input())
graph = [[] for i in range(n + 1)]
edge = []
for i in range(n - 1):
    a, b = map(int, input().split())
    edge.append((a, b))
    graph[a].append(b)
    graph[b].append(a)
color = [None for i in range(n - 1)]
queue = collections.deque([(1, 0)])
while queue:
    temp = queue.popleft()
    num = temp[0]
    prev = temp[1]
    if prev:
        col = color[edge.index((min(num, prev), max(num, prev)))]
    else:
        col = 0
    count = 1
    for i in graph[num]:
        a, b = min(i, num), max(i, num)
        temp = edge.index((a, b))
        if color[temp] != None:
            continue
        else:
            if count == col:
                color[temp] = count + 1
                count += 2
            else:
                color[temp] = count
                count += 1
            queue.append((i, num))
print(max(color))
for i in range(n - 1):
    print(color[i])

Submission status: Time Limit Exceeded

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

n = int(input())
graph = [[] for i in range(n + 1)]
edge = []
for i in range(n - 1):
    a, b = map(int, input().split())
    edge.append((a, b))
    graph[a].append(b)
    graph[b].append(a)
color = [None for i in range(n - 1)]
queue = collections.deque([[1, 0]])
while queue:
    temp = queue.popleft()
    num = temp[0]
    prev = temp[1]
    if prev:
        col = color[edge.index((min(num, prev), max(num, prev)))]
    else:
        col = 0
    count = 1
    for i in graph[num]:
        a, b = min(i, num), max(i, num)
        temp = edge.index((a, b))
        if color[temp] != None:
            continue
        else:
            if count == col:
                color[temp] = count + 1
                count += 2
            else:
                color[temp] = count
                count += 1
            queue.append([i, num])
print(max(color))
for i in range(n - 1):
    print(color[i])

Submission status: Time Limit Exceeded

Solution code:
import collections

n = int(input())
graph = [[] for i in range(n + 1)]
edge = []
for i in range(n - 1):
    a, b = map(int, input().split())
    edge.append((a, b))
    graph[a].append(b)
    graph[b].append(a)
color = [None for i in range(n - 1)]
queue = collections.deque([[1, 0]])
while queue:
    temp = queue.popleft()
    num = temp[0]
    prev = temp[1]
    if prev:
        col = color[edge.index((min(num, prev), max(num, prev)))]
    else:
        col = 0
    count = 1
    for i in graph[num]:
        a, b = min(i, num), max(i, num)
        temp = edge.index((a, b))
        if color[temp] != None:
            continue
        else:
            if count == col:
                color[temp] = count + 1
                count += 2
            else:
                color[temp] = count
                count += 1
            queue.append([i, num])
print(max(color))
for i in range(n - 1):
    print(color[i])

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10**9)


def dfs(s, to, color, palette, i=0):
    seen[s] = 1
    for v in to[s]:
        if seen[v]:
            continue
        if s < v:
            color[sides.index([s, v])] = palette[i % len(palette)]
            i += 1
        dfs(v, to, color, palette, i)


N = int(input())
sides = [list(map(lambda x:int(x) - 1, input().split())) for _ in range(N - 1)]
to = [[] for _ in range(N)]
for a, b in sides:
    to[a].append(b)
    to[b].append(a)
colors_used = max(len(sub) for sub in to)
palette = [i for i in range(1, colors_used+1)]
seen = [0] * N
color = [0] * (N - 1)

dfs(0, to, color, palette)

print(colors_used)
print(*color, sep='\n')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N=int(input())
E={i:set() for i in range(1,N+1)}
F=[0]*(N+1)

H=[0]*(N-1)
J={}
for s in range(N-1):
    a,b=map(int,input().split())
    E[a].add(b)
    E[b].add(a)
    F[a]+=1
    F[b]+=1
    H[s]=(a,b)
    J[(a,b)]=s

C=[0]*(N-1)
G=[set() for _ in range(N+1)]

T={i:False for i in range(1,N+1)}
T[2]=True
Q=deque([2])
while Q:
    v=Q.popleft()
    for w in E[v]:
        if not T[w]:
            T[w]=True
            Q.append(w)

            p,q=min(v,w),max(v,w)
            c=1
            while c in G[p] or c in G[q]:
                c+=1
            C[J[(p,q)]]=c
            G[p].add(c)
            G[q].add(c)

print(max(C))
print("\n".join(map(str,C)))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N=int(input())
E={i:set() for i in range(1,N+1)}
F=[0]*(N+1)

H=[0]*(N-1)
J={}
for s in range(N-1):
    a,b=map(int,input().split())
    E[a].add(b)
    E[b].add(a)
    F[a]+=1
    F[b]+=1
    H[s]=(a,b)
    J[(a,b)]=s

C=[0]*(N-1)
G=[set() for _ in range(N+1)]

T={i:False for i in range(1,N+1)}
T[1]=True
Q=deque([1])
while Q:
    v=Q.popleft()
    for w in E[v]:
        if not T[w]:
            T[w]=True
            Q.append(w)

            p,q=min(v,w),max(v,w)
            c=1
            while c in G[p]|G[q]:
                c+=1
            C[J[(p,q)]]=c
            G[p].add(c)
            G[q].add(c)

print(max(C))
print("\n".join(map(str,C)))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N=int(input())
E={i:set() for i in range(1,N+1)}
F=[0]*(N+1)

H=[0]*(N-1)
J={}
for s in range(N-1):
    a,b=map(int,input().split())
    E[a].add(b)
    E[b].add(a)
    F[a]+=1
    F[b]+=1
    H[s]=(a,b)
    J[(a,b)]=s

C=[0]*(N-1)
G=[set() for _ in range(N+1)]

T={i:False for i in range(1,N+1)}
T[1]=True
Q=deque([1])
while Q:
    v=Q.popleft()
    for w in E[v]:
        if not T[w]:
            T[w]=True
            Q.append(w)

            p,q=min(v,w),max(v,w)
            c=1
            while c in G[p] or c in G[q]:
                c+=1
            C[J[(p,q)]]=c
            G[p].add(c)
            G[q].add(c)

print(max(C))
print("\n".join(map(str,C)))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**7)
import bisect
import heapq
import itertools
import math
import numpy as np
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from math import gcd
from operator import add, itemgetter, mul, xor
def cmb(n,r,mod):
  bunshi=1
  bunbo=1
  for i in range(r):
    bunbo = bunbo*(i+1)%mod
    bunshi = bunshi*(n-i)%mod
  return (bunshi*pow(bunbo,mod-2,mod))%mod
mod = 10**9+7
def I(): return int(input())
def LI(): return list(map(int,input().split()))
def MI(): return map(int,input().split())
def LLI(n): return [list(map(int, input().split())) for _ in range(n)]

n = I()
#edge[i][j]には頂点iと頂点jをつなぐ辺の色を格納する
edge = [[0]*(n+1) for _ in range(n+1)]
#graph[i]には頂点iと繋がっている頂点を格納する
graph = [[] for _ in range(n+1)]
prev_col = [0]*(n+1)
k = 0
a_b = []
for i in range(n-1):
    a,b = MI()
    a_b.append([a,b])
    graph[a].append(b)
    graph[b].append(a)
#check[i] == -1ならば未探索
check = [-1]*(n+1)
check[0] = 0
check[1] = 0
for i in range(n+1):
    k = max(len(graph[i]),k)
d = deque()
d.append(1)
while d:
    v = d.popleft()
    check[v] = 1
    cnt = 0
    for i in graph[v]:
      if check[i] != -1:
        continue
      cnt = cnt+1
      if prev_col[v] == cnt:
        cnt = cnt + 1
      edge[i][v] = cnt
      edge[v][i] = cnt
      prev_col[i] = cnt
      d.append(i)
      check[i] = 0
print(k)
for i in range(n-1):
    color = edge[a_b[i][0]][a_b[i][1]]
    print(color)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**7)
import bisect
import heapq
import itertools
import math
import numpy as np
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from math import gcd
from operator import add, itemgetter, mul, xor
def cmb(n,r,mod):
  bunshi=1
  bunbo=1
  for i in range(r):
    bunbo = bunbo*(i+1)%mod
    bunshi = bunshi*(n-i)%mod
  return (bunshi*pow(bunbo,mod-2,mod))%mod
mod = 10**9+7
def I(): return int(input())
def LI(): return list(map(int,input().split()))
def MI(): return map(int,input().split())
def LLI(n): return [list(map(int, input().split())) for _ in range(n)]

n = I()
#edge[i][j]には頂点iと頂点jをつなぐ辺の色を格納する
edge = [[0]*(n+1) for _ in range(n+1)]
#graph[i]には頂点iと繋がっている頂点を格納する
graph = [[] for _ in range(n+1)]
prev_col = [0]*(n+1)
k = 0
a_b = []
for i in range(n-1):
    a,b = MI()
    a_b.append([a,b])
    graph[a].append(b)
    graph[b].append(a)
#check[i] == -1ならば未探索
check = [-1]*(n+1)
check[0] = 0
check[1] = 0
d = deque()
d.append(1)
while d:
    v = d.popleft()
    check[v] = 1
    cnt = 0
    for i in graph[v]:
      if check[i] != -1:
        continue
      cnt = cnt+1
      if prev_col[v] == cnt:
        cnt = cnt + 1
      edge[i][v] = cnt
      edge[v][i] = cnt
      prev_col[i] = cnt
      d.append(i)
      check[i] = 0
      k = max(k,cnt)
print(k)
for i in range(n-1):
    color = edge[a_b[i][0]][a_b[i][1]]
    print(color)