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:
import sys, math

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

def main():
    N = int(input())
    T = []
    G = [[] for k in range(N+1)]
    for k in range(N-1):
        a, b = map(int,input().split())
        G[a].append(b)
        G[b].append(a)
        T.append(str(a)+"0"+str(b))

    V = [0 for k in range(N+1)]
    C = [set() for k in range(N+1)]
    ans = dict()
    m = 0
    V[1] = 1
    Q = [1]
    while len(Q) > 0:
        ima = Q.pop()
        for tsugi in G[ima]:
            if V[tsugi] == 0:
                V[tsugi] = 1
                t = 1
                while t in C[ima] or t in C[tsugi]:
                    t += 1
                m = max(m,t)
                C[ima].add(t)
                C[tsugi].add(t)
                ans[str(ima)+"0"+str(tsugi)] = t
                Q.append(tsugi)
    print(m)
    for e in T:
        print(ans[e])

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N, *AB = map(int, open(0).read().split())

E = [set() for _ in range(N + 1)]
for i, (a, b) in enumerate(zip(*[iter(AB)] * 2)):
    E[a].add((b, i))
    E[b].add((a, i))

K = max(len(e) for e in E)
A = [0] * (N - 1)
Q = deque([(-1, 1)])
S = {c for c in range(1, K + 1)}
while Q:
    p, v = Q.popleft()
    C = S - {p}
    for u, i in E[v]:
        E[u].remove((v, i))
        c = C.pop()
        Q.append((c, u))
        A[i] = c

print(K)
for a in A:
    print(a)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


N = int(input())
branch = [[0] + list(map(lambda x: int(x) - 1, input().split())) for _ in range(N - 1)]
vertex = [False] * N


def bfs():
    max_color = 0
    q = deque()
    v = 0
    bc = 0
    q.append((v, bc))

    while len(q):
        v, bc = q.popleft()
        vertex[v] = True
        b_list = [c for c in branch if v in c[1:]]

        color = 1
        for c in b_list:
            if color == bc:
                color += 1
            if (c[0] == 0):
                c[0] = color
                color += 1
            nv = c[1] if c[2] == v else c[2]
            if vertex[nv] is False:
                q.append((nv, c[0]))
        max_color = max(max_color, color - 1)

    return max_color


print(bfs())
for b in branch:
    print(b[0])

Submission status: Time Limit Exceeded

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

n = int(input())

edges = [[] for _ in range(n)]
l = []
for i in range(n-1):
    a,b = map(int,input().split())
    edges[a-1].append(b-1)
    edges[b-1].append(a-1)
    l.append([a-1,b-1])


ans = [[0 for _ in range(n)] for __ in range(n)]
visited = [False]*n

q = deque([(0,0)])
visited[0] = True

mx = 0
while q:
    key,v = q.popleft()
    i = 1
    for x in edges[v]:
        if not visited[x]:
            if key != i:
                visited[x] = True
                ans[v][x] = i
                ans[x][v] = i
                q.append((i,x))
                mx = max(mx,i)
                i += 1
            else:
                visited[x] = True
                i += 1
                ans[v][x] = i
                ans[x][v] = i
                q.append((i,x))
                mx = max(mx,i)
                i += 1

print(mx)
for i in range(n-1):
    print(ans[l[i][0]][l[i][1]])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


N = int(input())
branch = [[0] + list(map(lambda x: int(x) - 1, input().split())) for _ in range(N - 1)]
branch_color = [0] * (N - 1)
vertex = [False] * N


def bfs():
    max_color = 0
    q = deque()
    v = 0
    bc = 0
    q.append((v, bc))

    while len(q):
        v, bc = q.popleft()
        vertex[v] = True
        b_list = [c for c in branch if v in c[1:]]

        color = 1
        for c in b_list:
            if color == bc:
                color += 1
            if (c[0] == 0):
                c[0] = color
                color += 1

        max_color = max(max_color, color - 1)

        for c in b_list:
            nv = c[1] if c[2] == v else c[2]
            if vertex[nv] is False:
                q.append((nv, c[0]))

    return max_color


print(bfs())
for b in branch:
    print(b[0])

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
edge = []
for i in range(n-1):
    x,y = map(int,input().split())
    edge.append((x,y))

e = sorted(edge)
ex = []
for i in range(n):
    ex.append(set())

colors = dict()
count = [0]*n
num_color = 0
for l,r in e:
    count[l-1] += 1
    count[r-1] += 1
    cand = 1
    while cand in ex[l-1] or cand in ex[r-1]:
        cand += 1
    ex[l-1].add(cand)
    ex[r-1].add(cand)
    colors[(l,r)] = cand
print(max(count))
for a in edge:
    print(colors[a])

Submission status: Time Limit Exceeded

Solution code:
import collections
import sys
input = sys.stdin.readline
N = int(input())
ab = [list(map(int, input().split())) for i in range(N-1)]
eda = [set() for i in range(N)]
for a, b in ab:
    eda[a-1].add(b)
    eda[b-1].add(a)
max_e = 0
for i in range(N-1):
    max_e = max(max_e, len(eda[i]))
id = 0
for i in range(N):
    if len(eda[i]) == max_e:
        id = i

ans = [1]*(N-1)
q = collections.deque()
q.append(id)
print(max_e)
ans = [[0]*N for i in range(N)]
eda2 = [{i for i in range(1, max_e+1)} for j in range(N)]
g = [set() for i in range(N)]

for a, b in ab:
    g[a-1].add(b-1)
    g[b-1].add(a-1)
while(q):
    x = q.popleft()
    for y in g[x]:
        z = eda2[x].pop()
        ans[x][y] = z
        ans[y][x] = z
        eda2[y].remove(z)
        q.append(y)
        g[y].remove(x)
for a, b in ab:
    print(ans[a-1][b-1])

Submission status: Time Limit Exceeded

Solution code:
import collections
import sys
input = sys.stdin.readline
N = int(input())
ab = [list(map(int, input().split())) for i in range(N-1)]
eda = [set() for i in range(N)]
for a, b in ab:
    eda[a-1].add(b)
    eda[b-1].add(a)
max_e = 0
for i in range(N-1):
    max_e = max(max_e, len(eda[i]))
id = 0
for i in range(N):
    if len(eda) == max_e:
        id = i

ans = [1]*(N-1)
q = collections.deque()
q.append(id)
print(max_e)
ans = [[0]*N for i in range(N)]
eda2 = [{i for i in range(1, max_e+1)} for j in range(N)]
g = [set() for i in range(N)]

for a, b in ab:
    g[a-1].add(b-1)
    g[b-1].add(a-1)
while(q):
    x = q.popleft()
    for y in g[x]:
        z = eda2[x].pop()
        ans[x][y] = z
        ans[y][x] = z
        eda2[y].remove(z)

        q.append(y)
        g[y].remove(x)
for a, b in ab:
    print(ans[a-1][b-1])

Submission status: Time Limit Exceeded

Solution code:
from functools import reduce
from operator import mul
N = int(input())
ab = [tuple(map(int, input().split())) for _ in range(N-1)]
E_n = {k: 0 for k in ab}
for i in range(1,N+1):
    items = {k:v for k,v in E_n.items() if i in k}
    c = 1
    if items == {}: continue
    elif reduce(mul, items.values()) != 0: continue
    for k in items.keys():
      if items[k] != 0: continue
      while True:
        if c not in items.values():
          items[k] = c
          break
        else: c += 1
    E_n.update(items)
    #if reduce(mul, E_n.values()) != 0: break

print(len(set(E_n.values())))
for k in ab: print(E_n[k])

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(1,N)]
nd=[0 for _ in range(N)]
table = [[] for _ in range(N)]
for a,b in AB:
  table[a-1].append(b)
  nd[a-1]+=1
  nd[b-1]+=1

K=max(nd)
co=[0 for _ in range(N)]
for x,li in enumerate(table):
  c=[i for i in range(1,K+1) if i != co[x]]
  for b,y in zip(li,c):
    co[b-1]=y

print(K)
for _,b in AB:
  print(co[b-1])

Submission status: Time Limit Exceeded

Solution code:
import collections
from collections import defaultdict
N = int(input())
edges = []
vertexes = []
count = defaultdict(int)
parent = {}
childs = defaultdict(list)
color_dict = defaultdict(dict)
for i in range(N-1):
  a, b = map(int, input().split())
  parent[b] = a
  childs[a].append(b)
  edges.append((a,b))
  vertexes.append(a)
  vertexes.append(b)
  
#print(edges)
#print(vertexes)
#print(parent)
#childs = dict(childs)
#print(childs)

c = collections.Counter(vertexes)
max_color = max(c.values())
print(max_color)

parent_color = {1: -1}
for i in range(1, N):
  if i not in childs:
    continue
  pc = parent_color[i]
  allowed_colors = [j for j in range(1, max_color + 1) if j != pc]
  for child, color in zip(childs[i], allowed_colors):
    color_dict[i][child] = color
    parent_color[child] = color
    
#print(color_dict)

for e in edges:
  print(color_dict[e[0]][e[1]])

Submission status: Time Limit Exceeded

Solution code:
from functools import reduce
from operator import mul
N = int(input())
ab = [tuple(map(int, input().split())) for _ in range(N-1)]
E_n = {k: 0 for k in ab}
for i in range(1,N+1):
    items = {k:v for k,v in E_n.items() if i in k}
    c = 1
    if reduce(mul, items.values()) == 0:
      for k in items.keys():
        if items[k] != 0: continue
        while True:
          if c not in items.values():
            items[k] = c
            break
          else: c += 1
      for k,v in items.items(): E_n[k] = v
    if reduce(mul, E_n.values()) != 0: break

print(len(set(E_n.values())))
for k in ab: print(E_n[k])

Submission status: Time Limit Exceeded

Solution code:
iro = []
res = []
r = 0
cc = {}
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 in iro:
      cr += 1
      continue
    elif b in iro:
      cr += 1
      continue
    elif 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)]

eda = [set() for i in range(N)]

for a, b in ab:
    eda[a-1].add(b)
    eda[b-1].add(a)
max_e = 0
for i in range(N-1):
    max_e = max(max_e, len(eda[i]))
id = 0
for i in range(N):
    if len(eda) == max_e:
        id = i

ans = [1]*(N-1)
q = collections.deque()
q.append(id)
print(max_e)
ans = [[0]*N for i in range(N)]
eda2 = [{i for i in range(1, max_e+1)} for j in range(N)]
g = [set() for i in range(N)]

for a, b in ab:
    g[a-1].add(b-1)
    g[b-1].add(a-1)
while(q):
    x = q.popleft()
    for y in g[x]:
        for z in eda2[x]:
            ans[x][y] = z
            ans[y][x] = z
            eda2[x].remove(z)
            eda2[y].remove(z)
            break

        q.append(y)
        g[y].remove(x)
for a, b in ab:
    print(ans[a-1][b-1])

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
edges = [[] for i in range(N)]
ans = [[0 for i in range(N + 1)] for i in range(N + 1)]
lines = []

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

q = [(0, 0,)]
max_color = 0
while q:
    v, color = q.pop()
    c = 0
    for nv in edges[v]:
        c += 1
        if c == color:
            c += 1
        q.append((nv, c,))
        ans[v + 1][nv + 1] = c
        max_color = max(max_color, c)

print(max_color)
for i in range(N - 1):
    a, b = lines[i]
    print(ans[a][b])

Submission status: Time Limit Exceeded

Solution code:
import collections
N = int(input())

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

eda = [set() for i in range(N)]

for a, b in ab:
    eda[a-1].add(b)
    eda[b-1].add(a)
max_e = 0
for i in range(N-1):
    max_e = max(max_e, len(eda[i]))
id = 0
for i in range(N):
    if len(eda) == max_e:
        id = i

ans = [1]*(N-1)
q = collections.deque()
q.append(id)
print(max_e)
ans = [[0]*N for i in range(N)]
eda2 = [{i for i in range(1, max_e+1)} for j in range(N)]
g = [set() for i in range(N)]

for a, b in ab:
    g[a-1].add(b-1)
    g[b-1].add(a-1)
while(q):
    x = q.popleft()
    for y in g[x]:
        for z in eda2[x]:
            if z in eda2[y]:
                ans[x][y] = z
                ans[y][x] = z
                eda2[x].remove(z)
                eda2[y].remove(z)
                break

        q.append(y)
        g[y].remove(x)
for a, b in ab:
    print(ans[a-1][b-1])

Submission status: Time Limit Exceeded

Solution code:
import queue
n = int(input())

#ab = [[]*(n)]
ab = [[] for _ in range(n+1)]
#print(ab)

li = []

for i in range(n-1):
    a,b = map(int,input().split())
    ab[a].append(b)
    ab[b].append(a)
    li.append([a,b])
    
ab_color = [[0 for _ in range(n+1)] for _ in range(n+1)]

#print(li)

q = queue.Queue()
check = [0] * (n+1)
#check[1] == 1
check_color = [0] * (n+1)

q.put(1)
color_num = 1
#mae_color = 0

while not q.empty():
    tmp_color = 0
    tmp = q.get()
    #print(tmp)
    #tmp_color = mae_color
    mae_color = check_color[tmp]
    for i in range(len(ab[tmp])):
        if check[ab[tmp][i]] == 1:
            #print(i,tmp)
            continue
        else:
            #print(mae_color,tmp_color,tmp,i)
            tmp_color += 1
            q.put(ab[tmp][i])
            if tmp_color == mae_color:
                tmp_color += 1
            check_color[ab[tmp][i]] = tmp_color
            ab_color[ab[tmp][i]][tmp] = tmp_color
            ab_color[tmp][ab[tmp][i]] = tmp_color
            check[tmp] = 1
            if color_num < tmp_color:
                color_num = tmp_color
            #color_num = max(color_num,tmp_color)
            #print(check,i)

print(color_num)
for i in range(len(li)):
    print(ab_color[li[i][0]][li[i][1]])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline
n = int(input())
g = [[] for i in range(n)]
l = [0] * (n-1)
for _ in range(n-1):
  a,b = map(int,input().split())
  a,b = a-1,b-1
  l[_] = (min(a,b),max(a,b))
  g[a].append(b)
  g[b].append(a)
m = 0
for _ in range(n):
  if len(g[_]) > m:
    m = len(g[_])
    mi = _
print(m)
g2 = [set(range(1,m+1)) for i in range(n)]
deq = deque([mi])
vi = [0] * n
vi[mi] = 1
d = dict()
while deq:
  cur = deq.popleft()
  for i in g[cur]:
    if vi[i] == 1:
      continue
    else:
      vi[i] = 1
      deq.append(i)
      cu = (g2[cur]&g2[i]).pop()
      g2[cur].discard(cu)
      g2[i].discard(cu)
      d[(min(cur,i),max(cur,i))] = cu
for i in l:
  print(d[i])

Submission status: Time Limit Exceeded

Solution code:
#import sys
MOD = 10 ** 9 + 7
#input = sys.stdin.readline
import math

#import bisect

def sosuhante(n):
    for k in range(2, int(math.sqrt(n))+1):
        if n% k ==0:
            return False
    return True
def cmb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

def kingaku(a,b,n):
    keta=len(str(n))
    return a*n+b*keta

def main():
#    h,w,a,b = map(int, input().split())
    n=int(input())
    b = [[] for i in range(n)]
    c = [[0 for j in range(n)] for i in range(n)]
    d=[]
    for i in range(n-1):
        x,y=map(int,input().split())
        c[x-1][y-1]=-1
        c[y-1][x-1]=-1
        d.append([x,y])
#    print(c)

    for i in range(n):
        temp=[]
        for j in range(n):
            if c[i][j]==-1:
                for l in range(1,n):
                    if l not in temp:
                        c[i][j]=l
                        c[j][i]=l
                        temp.append(l)
                        break
            elif c[i][j]!=0:
                temp.append(c[i][j])
#    print(c)
    e=[]
    for i in range(n):
        e.append(max(c[i]))
    print(max(e))
    for i in range(n-1):
        print(c[d[i][0]-1][d[i][1]-1])

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())

l=[[0 for i in range(n-1)]for j in range(n)]
m=[0]*n
t=[]
w=[]
for p in range(n-1):
    e = list(map(int, input().split()))
    w.append(e)

for i in range(n-1):
    a=w[i][0]-1
    b=w[i][1]-1
    m[a] +=1
    m[b] +=1
    k=0
    while True:

        if l[a][k]==0 and l[b][k]==0:
            l[a][k]=1
            l[b][k]=1
            break
        else:
            k +=1
    t.append(k+1)

c=max(m)
print(c)
for g in range(n-1):
    print(t[g])

Submission status: Time Limit Exceeded

Solution code:
N=int(input());AB=[list(map(int,input().split())) for _ in range(1,N)]
nd=[0 for _ in range(N)]
table = [[] for _ in range(N)]
for a,b in AB:
  table[a-1].append(b)
  nd[a-1]+=1
  nd[b-1]+=1

K=max(nd)
co=[0 for _ in range(N)]
for x,li in enumerate(table):
  c=[i for i in range(1,K+1) if i != co[x]]
  for b,y in zip(li,c):
    co[b-1]=y

print(K)
for _,b in AB:
  print(co[b-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はそのまま使える）
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)

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


for i in range(1,N):
    for thing in graph[i]:
        j=thing[0]
        num=thing[1]

        c,cc=what_colour(cc,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(cc)
for thing in ret:
    print(thing)

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

Submission status: Time Limit Exceeded

Solution code:
import queue
n = int(input())

#ab = [[]*(n)]
ab = [[] for _ in range(n+1)]
#print(ab)

li = []

for i in range(n-1):
    a,b = map(int,input().split())
    ab[a].append(b)
    ab[b].append(a)
    li.append([a,b])
    
ab_color = [[0 for _ in range(n+1)] for _ in range(n+1)]

#print(li)

q = queue.Queue()
check = [0] * (n+1)
#check[1] == 1
check_color = [0] * (n+1)

q.put(1)
color_num = 1
#mae_color = 0

while not q.empty():
    tmp_color = 0
    tmp = q.get()
    #print(tmp)
    #tmp_color = mae_color
    mae_color = check_color[tmp]
    for i in range(len(ab[tmp])):
        if check[ab[tmp][i]] == 1:
            #print(i,tmp)
            continue
        else:
            #print(mae_color,tmp_color,tmp,i)
            tmp_color += 1
            q.put(ab[tmp][i])
            if tmp_color == mae_color:
                tmp_color += 1
            check_color[ab[tmp][i]] = tmp_color
            ab_color[ab[tmp][i]][tmp] = tmp_color
            ab_color[tmp][ab[tmp][i]] = tmp_color
            check[tmp] = 1
            color_num = max(color_num,tmp_color)
            #print(check,i)

print(color_num)
for i in range(len(li)):
    print(ab_color[li[i][0]][li[i][1]])

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):
    col = 1
    for t in L[target]:
        if t == parent:
            continue
        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())
HEN = []
COUNT = []
for i in range(N-1):
    tmp = [int(i) for i in input().split()]
    HEN.append(tmp)
    COUNT.append(tmp[0])
    COUNT.append(tmp[1])
    
MAX = 0
for i in range(1,N+1):
    tmp = COUNT.count(i) 
    if tmp > MAX:
        MAX = tmp
print(MAX)

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

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

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

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

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 = []
    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.append(color[basho[s]])
    all = [i for i in range(1, K+1)]
    sa = list(set(all) - set(colk))
    now = 0
    for s in NN:
        if not basho[s] in color.keys():
            color[basho[s]] = sa[now]
            now += 1

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
ab = []
graph = {(i + 1):[] for i in range(n)}
for i in range(n - 1):
    a, b = map(int, input().split())
    ab.append([a, b])
    graph[a].append(b)
    graph[b].append(a)
color = max([len(list(graph.values())[i]) for i in range(n)])
print(color)
branch = {}
for i in graph:
    if len(graph[i]) == color:
        start = i
        break
task = [[start, 0]]
while task:
    next_check = task.pop(0)
    check = next_check[0]
    flag = False
    temp = []
    for i in range(len(graph[check])):
        if i + 1 == next_check[1]:
            flag = True
        branch[(check, graph[check][i])] = i + 1 + flag
        task.append([graph[check][i], i + 1 + flag])
        temp.append([check, graph[check][i]])
    for i in temp:
        graph[i[0]].remove(i[1])
        graph[i[1]].remove(i[0])
for i in ab:
    if (i[0], i[1]) in branch:
        print(branch[(i[0], i[1])])
    else:
        print(branch[(i[1], i[0])])

Submission status: Time Limit Exceeded

Solution code:
N=int(input());AB=[list(map(int,input().split())) for _ in range(1,N)]
nd=[0 for _ in range(N)]
table = [[] for _ in range(N)]
for a,b in AB:
  table[a-1].append(b)
  nd[a-1]+=1
  nd[b-1]+=1

K=max(nd)
co=[0 for _ in range(N)]
ans=dict()
for x,li in enumerate(table):
  c=[i for i in range(1,K+1) if i != co[x]]
  for b,y in zip(li,c):
    co[b-1]=y
    ans[(x+1,b)]=y

print(K)
for a,b in AB:
  print(ans[(a,b)])

Submission status: Time Limit Exceeded

Solution code:
N=int(input());AB=[list(map(int,input().split())) for _ in range(1,N)]
nd=[0 for _ in range(N)]
table = [[] for _ in range(N)]
for a,b in AB:
  table[a-1].append(b)
  nd[a-1]+=1
  nd[b-1]+=1

for li in table:
  li.sort()

K=max(nd)
print(K)
co=[0 for _ in range(N)]
ans=dict()
for x,li in enumerate(table):
  c=[i for i in range(1,K+1) if i != co[x]]
  for b,y in zip(li,c):
    co[b-1]=y
    ans[(x+1,b)]=y

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

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]

    col = 1
    for t in l:
        if t == parent:
            continue
        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:
def main():
    n = int(input())
    colors = [1]*(n+1)
    all_edges = {}
    nodes = {}
    order = []
    edges = []
 
    for i in range(1,n+1):
        nodes[i] = []
        
    for i in range(n-1):
        a,b = map(int,input().split())
        nodes[a].append(b)
        nodes[b].append(a)
        all_edges[(a,b)] = 0
        order.append((a,b))
        edges.append((a,b))

    k = 0
    for i in nodes.keys():
        k = max(k,len(nodes[i]))

    visited = set()
    for i in range(1,n):
        if i not in visited:
            visited.add(i)
            avail = []
            if i == 1:
                limit = colors[i]+1
            else:
                limit = colors[i]
            for j in range(1,limit):
                avail.append(j)
            for j in range(colors[i]+1,k+1):
                avail.append(j)
            #print(i,avail)
            for kid in nodes[i]:
                if kid not in visited:
                    #print(i,kid)
                    all_edges[(i,kid)] = avail.pop()
                    colors[kid] = all_edges[(i,kid)]

    print(k)
    for i in order:
        print(all_edges[i])
    
    
 
main()

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
  c = 1
  i = 1
  while i <= K:
    if not (i in V[a]):
      c = i
      req_K = False
      break
    i += 1
  if req_K:
    K += 1
    c = K
  V[a].append(c)
  V[b].append(c)
  ans[e] = c
print(K)
for e in E:
  print(ans[e])

Submission status: Time Limit Exceeded

Solution code:
import sys

N = int(sys.stdin.buffer.readline())

neighbor = [[] for _ in range(N)]
edge = []
for i in range(N-1):
    a, b = map(int, sys.stdin.buffer.readline().split())
    neighbor[a-1].append(b-1)
    neighbor[b-1].append(a-1)
    edge.append([a-1, b-1, i])

K = len(max(neighbor, key=len))
print(K)
color = [set(range(1, K+1)) for _ in range(N)]

edge = sorted(edge, key = lambda x:x[0])
for idx in range(N-1):
    c = color[edge[idx][0]].pop()
    edge[idx].append(c)
    color[edge[idx][1]].remove(c)

edge = sorted(edge, key=lambda x: x[2])
for x in edge:
    print(x[-1])

Submission status: Time Limit Exceeded

Solution code:
#d
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:
            current_color=list(set(color_list)-set(used_colors[parent-1]))[0]
            
            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())
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][tmp-1]=N+1
    graph[j][tmp-1]=N+1
print(max(a_list))
for i in a_list:
    print(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)
k = 0
for i in graph:
    if k< len(i):
        k = len(i)

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 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())
edges = [[] for _ in range(N)]
cnt_edges = [0]*N
colors = [0]*(N-1)
di = {}
A = []
K = 0
for i in range(N-1):
    a,b = [int(x) for x in input().split()]
    edges[a-1].append(b-1)
    edges[b-1].append(a-1)

    cnt_edges[a-1]+=1
    cnt_edges[b-1]+=1
    di[(a-1,b-1)] = i
    di[(b-1,a-1)] = i
    A.append((a-1,b-1))
#%%
K = max(cnt_edges)

stk = [(0,0)]
seen = set()
while(stk):
    n,used_color = stk.pop()
    available_color = [i for i in range(1,K+1)]
    if(used_color!=0):
        available_color.remove(used_color)
    next_stk = []
    for next in edges[n]:
        if(next in seen):
            continue
        col = available_color.pop()
        next_stk.append((next,col))
        i = di[(next,n)]
        colors[i] = col
    stk = next_stk + stk
    seen.add(n)

print(K)
for col in colors:
    print(col)