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.
Examples
Input
3
1 2
2 3
Output
2
1
2
Input
8
1 2
2 3
2 4
2 5
4 7
5 6
6 8
Output
4
1
2
3
4
1
1
2
Input
6
1 2
1 3
1 4
1 5
1 6
Output
5
1
2
3
4
5
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to output a proper edge-coloring of a tree such that at each vertex, incident edges have distinct colors. The minimum number of colors needed is the maximum degree of the tree (Δ). This is classic: since it's a tree (bipartite), edge chromatic number equals Δ (Vizing's theorem gives Δ for bipartite graphs, and trees are bipartite). So K = Δ.
We need to construct such a coloring using exactly Δ colors, labels 1..K. The tree can have up to 1e5 vertices, so we need O(N) algorithm.
One simple approach: Root the tree at some node (say 1). Perform DFS from root. For each node, when processing its children edges, assign colors to edges to children that are not used by its parent edge (if any). Since the maximum degree is Δ, we have enough colors.
Specifically, let parent edge of node u (if u is not root) have color pcolor. Then for its children edges, we need to assign distinct colors from the set {1..Δ} that are not pcolor. The number of children is deg(u)-1 (if u not root) or deg(u) (if root). Since deg(u) ≤ Δ, we can always pick distinct colors different from pcolor because Δ-1 >= deg(u)-1? Actually: For a non-root node u, incident edges: one to parent, and children edges to its children (deg(u)-1 children). We need to assign colors to children edges such that all colors are distinct and not equal to pcolor. There are Δ-1 colors available excluding pcolor, and we need to assign at most deg(u)-1 ≤ Δ-1 colors. So it's feasible. For the root, no parent edge, so we need to assign colors to all its incident edges (deg(root) ≤ Δ) using distinct colors from 1..Δ. So it's feasible.
Implementation: We'll first compute degree of each node, find Δ. Then we do DFS/BFS. For each node, we have list of adjacent edges (with edge index). We'll keep track of used colors at the node: we know the color of the edge to its parent (if any). For children, we can iterate through adjacent edges except parent, assign colors sequentially but skipping the parent color. But we need to ensure that for a given child, we assign a color that hasn't been used for other children already. Since we assign in order, we can maintain a pointer to the next color, skipping parent color and colors already used. Since we assign to each child one by one, we can just use a variable cur = 1, then for each child, if cur == pcolor, increment cur; assign that color; then increment cur. But careful: we need to ensure we never exceed Δ, but since number of children ≤ Δ-1 (or Δ for root), and we have enough colors, this will work. However, we must also consider that cur might need to wrap? But we can just assign the smallest available colors distinct from pcolor. This greedy works because we have exactly Δ colors and at most Δ-1 children for non-root.
But caution: For root, there is no pcolor, so we assign colors 1..deg(root) to its incident edges. That's fine.
One more nuance: The edge coloring must be consistent: The color assigned to an edge is the same from both endpoints perspective. Our DFS assigns color when processing the parent->child edge. So that's fine.
Thus algorithm:
Read N, edges. Store adjacency list: for each node, list of (neighbor, edge_index).
Compute degree array, find max_degree = K.
Root tree at 1.
Initialize color array of size N-1 (0-indexed).
Do DFS: function dfs(u, parent, parent_color) // parent_color is color of edge from parent to u (for root, parent_color = -1 or 0)
Let current color pointer c = 1.
For each (v, e_idx) in adj[u]:
if v == parent: continue.
if c == parent_color: c++ // skip parent color because we cannot use it for child edge (since need distinct at u)
assign color[e_idx] = c.
Then c++.
dfs(v, u, color[e_idx]).
However, note: At node u, we need to assign colors to children edges distinct from each other and from parent_color. The greedy with c increasing works as long as we skip parent_color. But is it possible that while iterating children, c may need to skip more than once because we might assign a color that later would conflict? Actually we only need to avoid parent_color; all other colors are free to use as long as they are distinct. So we can just assign consecutive integers, skipping parent_color. Since we have Δ colors, and number of children ≤ Δ-1, the assigned colors will be within 1..Δ, and distinct (since we increment after each assignment). This yields a proper edge coloring? Need to check property at child node v: When we go to v, its parent edge has color assigned. In v's DFS, it will assign colors to its children edges distinct from that parent color. This ensures at v, all incident edges have distinct colors because children edges have colors distinct from each other (since greedy) and distinct from parent color (since we skip). So condition holds.
Edge case: Suppose at node u, parent_color = some value p. We assign to children colors from a set that excludes p. But the children assignments might use colors that are also used by other edges incident to u? The only edges incident to u are parent edge and child edges, so we're fine. Also, the children edges are distinct colors, so condition satisfied at u.
Thus simple.
But is the number of colors used always exactly Δ? Actually we use colors up to possibly Δ, but maybe we use less than Δ if the max degree is Δ but we assign only up to some maximum used? Let's check: For root, we assign colors 1..deg(root) ≤ Δ, but if deg(root) < Δ, then max color used may be less than Δ? For example, a tree where max degree is at some internal node, not root. The root's degree might be 1, so we assign color 1 to its single edge. Then the node with degree Δ might be an internal node. When we color its incident edges, we have parent edge (maybe color something) and children edges. Since we skip parent color, we may need to use colors up to Δ. Let's simulate: Suppose Δ=3 at some node v, but root degree=1. At root (1) with neighbor 2: assign color 1 to edge (1-2). Then at node 2 (which may have degree 3): parent_color = 1. Children: two children. Using greedy: start c=1, skip 1? Actually we start c=1; first child: if c == parent_color? c=1, parent_color=1 => c=2; assign color 2 to first child edge; c=3. Next child: c=3, not equal to 1, assign color 3; c=4. So we used colors up to 3 = Δ. So indeed we may use Δ colors. However, could we use less? Possibly, but the problem asks for minimum number of colors, which is Δ. So output must have exactly Δ? Actually the problem says: "Among the colorings satisfying the condition, construct one that uses the minimum number of colors." The minimum number is Δ. So we should output using exactly Δ colors? It says "Print N lines. The first line should contain K, the number of colors used." So K should be the minimum possible, i.e., Δ. However, in some colorings with Δ colors, we may not actually use all Δ colors; but the number of colors used is the number of distinct colors present. The minimum possible distinct colors is Δ, so we must output a coloring that uses exactly Δ distinct colors? Actually the condition: we want to use the minimum number of colors. If we output a coloring that uses fewer than Δ distinct colors, that would be a contradiction because it's impossible to edge-color a tree with maximum degree Δ using fewer than Δ colors (by edge chromatic number for bipartite graphs). So any valid coloring must use at least Δ colors. So we must use exactly Δ distinct colors. However, is it possible that our greedy assignment might use less than Δ distinct colors? Let's see: In the above, we used colors 1,2,3. That's 3. Good. Consider a tree: star with center degree 5, Δ=5. Root at center, assign colors 1..5 to its edges -> uses all 5. Good. Consider a tree where max degree node is not root, but its parent edge might be colored with something, and we assign children colors from 1..Δ skipping parent. That might use all Δ colors if deg(max) = Δ and parent uses one color, children use the remaining Δ-1 distinct colors, but those Δ-1 colors might be chosen from 1..Δ excluding parent, so the union includes parent and children colors = Δ distinct colors if children colors cover all other Δ-1 colors. Could it happen that children colors do not cover all Δ-1? Possibly they could be a subset, but does that matter? The total distinct colors used overall might be less than Δ if the max degree node's parent color is some color and children use a set that does not include all other colors. However, the distinct colors used overall across the whole tree could still be Δ if there is some other node that forces use of the missing colors. But it's not guaranteed that our greedy will use all Δ colors; maybe it uses only, say, 2 colors for a tree with Δ=3? Let's test: Suppose a tree: 1-2, 2-3, 2-4. So Δ=2? Actually degrees: node2 degree 3? Wait edges: (1,2), (2,3), (2,4) -> deg(2)=3, so Δ=3. Nodes: 1,3,4 are leaves. Root at 1: assign edge(1,2) color1. At node2: parent_color=1. Children: node3 and node4. Greedy: c=1; skip parent_color (1) => c=2; assign color2 to (2,3); c=3; assign color3 to (2,4). So colors used: 1,2,3 -> Δ distinct. Good.
Consider a more complex tree: Δ=4, but maybe the max degree node is not root. Let's try to see if greedy can produce less than Δ distinct colors. Suppose node v has degree 4, its parent edge color p. It has 3 children. Greedy will assign colors to children as smallest available distinct from p. Starting c=1, skipping p when encountered. If p is, say, 2, then we assign to children: we start c=1, not p? c=1 !=2 so assign 1 to first child, c=2. Then skip p because c=2==p? yes, so c=3; assign 3 to second child, c=4; assign 4 to third child. So colors used at v: {2 (parent),1,3,4} = all four colors. If p=4, then: start c=1, assign 1; c=2, assign 2; c=3, assign 3; c=4, would be parent skip? Actually after third child, we have assigned three children, we stop before hitting c=4? Let's simulate: p=4. Start c=1, assign first child color1; c=2, assign second child color2; c=3, assign third child color3; we never need to use c=4 because we have only three children. So colors used at v: parent color 4, children colors 1,2,3 -> still all four colors? Actually we used colors {4,1,2,3} = all four colors. If p=1, then: start c=1 -> skip because c==p -> c=2; assign first child color2; c=3 assign second child color3; c=4 assign third child color4. So colors used: {1,2,3,4}. So indeed at node v with degree Δ, the set of colors incident will be all Δ colors because we have Δ edges and they must all be distinct. Since Δ edges at v must have Δ distinct colors, that forces the set of colors incident to v to be exactly Δ distinct colors. Therefore any valid edge-coloring of a graph where a vertex has degree Δ must use at least Δ colors, and actually at that vertex, all incident edges must have distinct colors, so they use Δ distinct colors locally. Hence globally, at least Δ distinct colors exist. Therefore any proper edge-coloring satisfying the condition automatically uses at least Δ distinct colors, and if we achieve proper coloring, the set of colors incident to that max-degree vertex will be exactly Δ distinct colors. So the global number of colors used is exactly Δ (since we only have Δ colors available and at that vertex we use Δ distinct ones). So we are safe: any valid coloring that meets the constraints must use exactly Δ distinct colors because at the vertex of degree Δ, all incident edges must have distinct colors, so they need Δ different colors; thus the coloring uses at least Δ colors, and we can limit our palette to exactly Δ colors. In our algorithm, we restrict colors to 1..Δ, and we will assign all Δ colors at the max-degree vertex (unless there is a situation where the max-degree vertex does not actually get all Δ colors because its incident edges might be colored with less than Δ distinct colors? But that's impossible because it has Δ edges and they all must be distinct, so they must use Δ distinct colors. So yes, it forces all Δ colors to appear. So K = Δ, and our coloring will use all Δ colors.
Thus algorithm works.
Now about implementation details: N up to 1e5, recursion depth might be N, which could cause stack overflow in Python if recursion depth > ~1000. So we need to use iterative DFS/BFS or increase recursion limit and hope it passes? Python recursion limit default is 1000. We can set sys.setrecursionlimit(200000). That's common for tree problems up to 1e5. It may be acceptable, but some judges might still have stack size limitations causing recursion depth error. Safer to use iterative stack. But using recursion with increased recursion limit is often fine in Python for 1e5 if it's not too deep (e.g., a long chain). Python recursion can cause RecursionError if depth > setrecursionlimit, but we can set it to 200000 or 300000. However, even with higher recursion limit, the C stack may overflow if recursion depth is too deep (depends on Python implementation and OS). Many Python solutions for tree problems use recursion with setrecursionlimit(10**6) and they pass. But to be safe, we can implement iterative DFS.
We'll implement BFS/stack to assign colors. Use parent array to traverse in order.
Approach: First do a BFS/DFS to compute parent order (like topological order). Then process nodes in that order (e.g., reverse BFS order) to assign colors from leaves up? But easier: we can do iterative stack that simulates DFS: push (node, parent, parent_color) and maintain a stack for traversal. However, we need to assign colors to children when processing a node. If we do a stack for DFS, we can push children after assigning colors. That is fine.
Pseudo:
adj = [list] size N+1.
edges: store as (a,b).
For i in range(N-1): read a,b; adj[a].append((b,i)); adj[b].append((a,i)).
stack = [(root, -1, 0)] # (node, parent, parent_edge_color) but for root parent_color not used. We'll use 0 as none.
while stack:
u, p, p_col = stack.pop()
Now assign colors to all edges except parent
c = 1
for v, e_idx in adj[u]:
if v == p: continue
if c == p_col: c += 1
colors[e_idx] = c
c += 1
# push child, with its parent color being colors[e_idx]
stack.append((v, u, colors[e_idx]))
But careful: Using stack LIFO, we assign colors and push children. That's fine, order doesn't matter.
One nuance: We skip p_col only when c equals it. But what if p_col is 0 (for root)? Then we never skip. Also, note that for root, p_col=0, and we assign colors starting from 1; it will assign up to deg(root). That's fine.
Check: When we assign colors for node u, we need to ensure that the colors we assign to children are distinct from p_col and each other. The simple increment skipping p_col works because we have enough colors: The maximum number of children is deg(u)-1 if p exists, else deg(u). We need to assign at most Δ-1 children colors. c starts at 1 and increments each time we assign. Since we skip only once for p_col, the maximum color we might assign is (number of children) plus possibly 1 if we skipped. Since number of children ≤ Δ-1, the maximum c after assignments is at most (Δ-1)+1 = Δ, which is within range. However, we might assign color values that exceed Δ if number of children is Δ (only possible for root) and we never skip p_col (since p_col=0), then c will go up to Δ+? Actually if root degree = Δ, we assign Δ children: start c=1, assign 1; c=2 assign2; ... assign Δ. So final c = Δ+1? Let's simulate: After assigning first child, c becomes 2; after second, c=3; ... after Δ-th child, c becomes Δ+1. So we assign colors 1..Δ, which are within 1..Δ. So we are fine. So the algorithm yields colors only in 1..Δ.
Now check correctness: At node u, we assign colors to children in some order. Suppose we have children v1,...,vk. We assign colors c1,c2,...,ck distinct and not equal to p_col. So at u, incident edges: parent edge color p_col (if exists), and child edges colors c_i, all distinct and different from p_col. So condition holds at u.
Now at child v, when we later process it, we will have parent_color = assigned color, and will assign to its children distinct colors from that. So condition holds recursively.
Thus algorithm is correct.
Time complexity: O(N), as each edge processed once.
Edge Cases: N=2, tree with one edge. Δ = 1 (since both vertices degree 1). Then K=1. Root at 1, p_col=0, assign color to edge (1,2) with c=1. So output: 1, then 1. Works.
N=3 star: 1-2,1-3. Δ = 2. Root 1: p_col=0, children: 2 and 3. assign colors: start c=1, assign edge (1,2) color1; c=2 assign edge (1,3) color2. Then process node2: p_col=1, its only child? Actually node2 has only neighbor 1 (parent), no children. So no assignment. Node3 similarly. Colors: 1,2 -> valid.
Now test given example 2:
8
1 2
2 3
2 4
2 5
4 7
5 6
6 8
Tree:
1-2
2-3
2-4
2-5
4-7
5-6
6-8
Degrees: node2 degree 4, so Δ=4. Output K=4. Let's simulate our algorithm with root=1.
But wait, edge4 already assigned color1? Actually earlier we assigned edge5 color1. That's fine; colors can be reused across non-adjacent edges. At node4, child edge (4-7) gets color1, even though edge (5-6) also color1. They are not incident to a common vertex (except maybe via path), which is fine. Condition is only per vertex.
Now (7,4,1): leaf.
Process (3,2,2): leaf.
So resulting colors:
edge0 (1-2): 1
edge1 (2-3): 2
edge2 (2-4): 3
edge3 (2-5): 4
edge4 (4-7): 1
edge5 (5-6): 1 (Wait we assigned 1? Actually we assigned color1 to edge5? In our above: at u=5 we assigned color1 to edge5. That is correct.)
edge6 (6-8): 2
But check example output: For edges in order:
1
2
3
4
1
1
2
Our output: 1,2,3,4,1,1,2 matches exactly. Good.
Thus algorithm works for the sample.
Now we should verify on a star with center degree 5: root=center, assign colors 1..5, ok.
Now about output format: print K on first line, then for each edge in input order (i from 0 to N-2) print color[i].
Implementation steps:
Read N.
Initialize adj = [[] for _ in range(N+1)]
edges list maybe not needed; but store adjacency with edge index.
For i in range(N-1):
read a,b
adj[a].append((b,i))
adj[b].append((a,i))
Compute deg: can compute on the fly while building adj.
Find K = max(len(adj[i]) for i in range(1,N+1)) (since each node degree is len(adj[i]))
Initialize colors = [0]*(N-1)
Use iterative stack (list) with (node, parent, parent_color). Starting with (1,0,0). We'll treat parent=0 (no node) and parent_color=0 (unused). Since colors are from 1..K, 0 is safe as sentinel.
While stack:
u, p, p_col = stack.pop()
c = 1
for v, e_idx in adj[u]:
if v == p: continue
if c == p_col:
c += 1
colors[e_idx] = c
# push child
stack.append((v, u, c))
c += 1
After loop, output K and then each color in colors list.
Potential pitfalls: The order of processing children influences which colors they get, but any valid coloring is accepted.
Now consider if there is any case where we need to skip parent color multiple times? No, because we only skip once when c equals p_col. But what if after skipping, later in the loop we encounter c again equals p_col? Since we increment c after assignment, c keeps increasing. Since we only have one p_col value, it can only equal it at most once because c is strictly increasing and p_col is fixed. So fine.
Edge case: When p_col is 0 (for root), we never skip because c never equals 0 (c starts at 1). So fine.
Now we need to ensure that c never exceeds K+1? It may go up to K+1 but we don't assign beyond K. Let's verify bound: For node u, number of children = ch = deg(u)-1 if p else deg(u). We assign ch colors. c starts at 1; after each assignment, c increments. If we skip once (if p exists and p_col <= ch+1 maybe?), the maximum value assigned is at most ch + (1 if skipped else 0). Since ch ≤ K-1 for non-root? Actually for non-root, deg(u) ≤ K, so ch = deg(u)-1 ≤ K-1. So ch + (1 if p_col <= ch+1?) worst-case we skip at the beginning: if p_col = 1, then we start with c=1 -> skip to c=2, then assign ch colors, so last assigned color = 1 (skip) + ch = ch+1. Since ch ≤ K-1, ch+1 ≤ K. Good. If p_col is larger, say p_col = ch+1, then we might assign colors 1..ch without hitting p_col, and last assigned = ch ≤ K-1? Actually if p_col > ch, we never skip, assign 1..ch, last = ch ≤ K-1 ≤ K. So all assignments are within 1..K. For root, ch = deg(root) ≤ K, we assign 1..ch ≤ K. So safe.
Thus algorithm is correct.
Now test on a chain: N=5: edges: 1-2,2-3,3-4,4-5. deg max = 2 (ends degree 1, internal degree 2). K=2. Root=1. Process 1: assign (1-2) color1. Process 2: p_col=1. children: 3. c=1 skip p_col? c==1 -> c=2 assign color2 to edge (2-3). Process 3: p_col=2. children: 4. c=1, not equal 2 assign color1 to edge (3-4). Process 4: p_col=1. children:5. c=1 skip? c==1 -> c=2 assign color2 to edge (4-5). Colors: 1,2,1,2. Check: each vertex: vertex2 edges colors 1 and2 distinct; vertex3 colors 2 and1 distinct; vertex4 colors 1 and2 distinct. Works.
Now implement.
Potential issues: Python recursion? Using iterative stack fine.
One more: Input size 1e5, use sys.stdin.read for fast input.
Implementation:
import sys
def main():
import sys
sys.setrecursionlimit(3000000) # just in case, but we use iterative.
data = sys.stdin.read().split()
it = iter(data)
n = int(next(it))
adj = [[] for _ in range(n+1)]
edges = [] # maybe not needed
for i in range(n-1):
a = int(next(it)); b = int(next(it))
adj[a].append((b,i))
adj[b].append((a,i))
# compute max degree
K = max(len(adj[i]) for i in range(1,n+1))
colors = [0]*(n-1)
# iterative DFS
stack = [(1,0,0)] # (node, parent, parent_edge_color)
while stack:
u, p, p_col = stack.pop()
c = 1
for v, e_idx in adj[u]:
if v == p:
continue
if c == p_col:
c += 1
colors[e_idx] = c
stack.append((v, u, c))
c += 1
# output
out = [str(K)]
out.extend(str(colors[i]) for i in range(n-1))
sys.stdout.write("\n".join(out))
if name == "main":
main()
Test on samples.
Sample 1:
3
1 2
2 3
Adj:
1: [(2,0)]
2: [(1,0),(3,1)]
3: [(2,1)]
K = max(len)=2 (node2 has degree 2)
stack: start (1,0,0)
pop (1,0,0): c=1; neighbor (2,0): v=2, not parent; c==0? no; assign colors[0]=1; push (2,1,1); c=2. Loop ends.
stack: [(2,1,1)]
pop (2,1,1): c=1; neighbors: (1,0) skip; (3,1): v=3, c==p_col? c=1, p_col=1 => c=2; assign colors[1]=2; push (3,2,2); c=3.
stack: [(3,2,2)]
pop (3,2,2): c=1; neighbors: (2,1) skip; no other, loop ends.
colors: [1,2] -> output K=2, then 1,2. matches.
Sample 2 we already matched.
Sample 3:
6
1 2
1 3
1 4
1 5
1 6
Star, K=5. Root=1: assign colors 1,2,3,4,5 in some order. Since adjacency list order could be 2,3,4,5,6 (based on input order). Input order edges: (1,2), (1,3), (1,4), (1,5), (1,6). Adj[1] will have entries: (2,0), (3,1), (4,2), (5,3), (6,4) likely. So c=1 assign color1 to edge0, c=2 assign color2 to edge1, c=3 assign color3 to edge2, c=4 assign color4 to edge3, c=5 assign color5 to edge4. So output: 5 then 1,2,3,4,5. That's valid.
So solution is ready.
But is it always possible to assign colors in a tree using this simple greedy without any lookahead? Yes, because tree is acyclic and we are essentially performing a proper edge-coloring with Δ colors by a simple DFS that always picks the smallest available color not used at the current node. This works because at each node we have at most Δ-1 used colors (only the parent edge) and we have Δ colors total, so we can always assign distinct colors to the remaining edges.
Thus this is a classic algorithm.
Now consider that the maximum degree might be large, up to N-1 (star). So K up to 1e5. That's fine.
Edge indexing: we need to output colors for edges in the order given. We stored colors array indexed by edge index (input order). So output works.
Now we must confirm that the coloring uses exactly K colors, i.e., all colors 1..K appear at least once. In our assignment, the vertex with max degree will have all incident edges colored with distinct colors, so that uses K colors. But could there be a case where the max-degree vertex is not the root, and due to our greedy, we might assign colors that are not all distinct? Wait, at the max-degree vertex, we must assign distinct colors to all incident edges. Our algorithm ensures at that vertex, the colors assigned to its incident edges (parent and children) are all distinct because we skip parent color for children and assign distinct colors to children. So the set of colors at that vertex will have size = degree(v). Since degree(v) = K, those K colors must be exactly K distinct colors. But could it happen that some color > K? No, we only use 1..K. Could it happen that some color among 1..K is not used at that vertex? Possibly if the set of colors assigned is a subset of {1..K} but of size K, that means it uses all K colors exactly once. Actually if you have K distinct numbers from 1..K, they must be exactly the set {1,...,K}. So all colors are used at that vertex. So overall coloring uses all K colors. Good.
Thus K = max degree is the answer.
Now about performance: The stack may have up to N elements. It's fine.
Now finalize solution.
But careful: In iterative DFS, we are using a stack LIFO, and we assign colors and push children. This is essentially a depth-first order. Could there be an issue if we assign colors to children and then later, when processing the child, we might need to know something about the sibling assignments? No, each node only cares about its parent edge color; the children assignments are independent.
Thus solution complete.
I'll produce final answer.
However, I want to consider alternative approach: BFS from root, assign colors in increasing order skipping parent's color. That's essentially same.
Now produce final answer: Explanation and code.
We'll include commentary in the final response as per instructions: "You are ChatGPT, a large language model... Provide the final answer." So we just output code? The problem expects just the output? Actually we need to write a solution? The user says: "We need to output a proper edge-coloring...". Actually the conversation seems like a problem statement and then we are to respond with solution? The user gave the problem statement and then "We need to output..."? Actually they are describing the problem. The final answer should be the code in Python. But the instruction says: "Provide the final answer." Likely they want the code. I'll output the Python code.
But I'm ChatGPT, I should output the solution as a code block.
Now final.
But before final, test edge cases:
N=2: Input: 2; 1 2. Our code: K = max(len(adj[1]), len(adj[2])) = 1. stack: (1,0,0): assign edge0 color1, push (2,1,1). Process 2: no children. Output: 1 and 1. OK.
Large star: N=100000, with center 1. K = 99999. Our code assigns colors 1..99999 sequentially. That's fine.
Long chain: N=100000, K=2, colors assigned alternating. Works.
Now check memory: adj list of size N+1, each edge stored twice, so about 2*(N-1) entries, each tuple (neighbor, index). Acceptable.
Now I'll output code with appropriate reading.
Potential improvement: Use sys.stdin.buffer.read() for speed, but the above is fine.
I'll set recursionlimit but we don't use recursion; still keep it for safety? Not needed. I'll remove recursionlimit or keep.
Now produce final answer:
python
import sys
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
adj = [[] for _ in range(n+1)]
for i in range(n-1):
a = int(next(it))
b = int(next(it))
adj[a].append((b, i))
adj[b].append((a, i))
K = max(len(adj[i]) for i in range(1, n+1))
colors = [0] * (n-1)
stack = [(1, 0, 0)] # node, parent, parent_edge_color
while stack:
u, p, p_col = stack.pop()
c = 1
for v, e_idx in adj[u]:
if v == p:
continue
if c == p_col:
c += 1
colors[e_idx] = c
stack.append((v, u, c))
c += 1
out = [str(K)]
out.extend(str(colors[i]) for i in range(n-1))
sys.stdout.write("\n".join(out))
if __name__ == "__main__":
main()
That's the solution.
I'll include explanation in the answer? The user said "Provide the final answer." So likely just code. But sometimes they want explanation. But the conversation started with "Given is a tree...". Probably they expect a solution. I'll output code and maybe brief explanation? The instruction: "Provide the final answer." I think it's safe to output the code with a brief comment.
Thus final.
```python
import sys
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
adj = [[] for _ in range(n + 1)]
code
# read edges, store with index
for idx in range(n - 1):
a = int(next(it))
b = int(next(it))
adj[a].append((b, idx))
adj[b].append((a, idx))
# maximum degree = minimal number of colors
K = max(len(adj[i]) for i in range(1, n + 1))
colors = [0] * (n - 1) # answer for each edge
stack = [(1, 0, 0)] # (node, parent, color of edge from parent)
while stack:
u, parent, parent_color = stack.pop()
cur = 1
for v, e_idx in adj[u]:
if v == parent:
continue
if cur == parent_color:
cur += 1
colors[e_idx] = cur
stack.append((v, u, cur))
cur += 1
out = [str(K)]
out.extend(str(colors[i]) for i in range(n - 1))
sys.stdout.write("\n".join(out))