<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

216. Royal Federation
time limit per test: 0.5 sec.
memory limit per test: 65536 KB
input: standard
output: standard



The king of Fooland has recently decided to reorganize his kingdom. Inspired by the democracy processes in neighbouring countries, he decided to convert his kingdom into Royal Federation. The Royal Federation would consist of several provinces, each headed by its governor.

There are N cities in his kingdom, numbered from 1 to N. Some cities are connected by roads. Roads are designed in such a way, that for each city there is exactly one way to get to any other city by the roads, not passing through any city more than once.

To prevent wastes for maintaining too small provinces, each province must contain at least B cities. However, to keep governments effective, each province must contain at most 3B cities.

Each province must have its governer headquaters in some city. This city may be outside the province itslef, but one must be able to get to the city with governer headquaters of his province in such a way, that all intermediate cities that he visits on his way belong to his province (and only the terminal city may be from another province).

One city may contain headquaters for several provinces.

Help the king to see his plans fulfilled.

Input

The first line of the input file contains two integer numbers — N and B (1 ≤ N ≤ 10 000, 1 ≤ B ≤ N). Next N-1 lines contain descriptions of roads, each line contains two integer numbers — the cities the road connects.

Output

If it is impossible to fulfil king's plans of reorganization, output 0 on the first line of the output file. In the other case output K — the number of provinces in your plan of the Royal Federation. After that output N integer numbers ranging from 1 to K — for each city output the number of the province it belongs to.

Finally output K integer numbers — the cities where the capitals of the provinces must be located in.

Sample test(s)

Input
8 2
1 2
2 3
1 8
8 7
8 6
4 6
6 5

Output
3
2 1 1 3 3 3 3 2
2 1 8
Author:	Andrew Stankevich
Resource:	Petrozavodsk Summer Trainings 2003
Date:	2003-08-30

<|response|>
1. Abridged Problem Statement  
Given a tree of N cities (nodes) and an integer B, partition the nodes into K connected provinces so that:  
  • Each province has size at least B and at most 3·B.  
  • Each province has a capital city (one per province). For any city u in province P, the unique path from u to P’s capital may leave P only at the final step (i.e., all intermediate nodes on that path lie inside P).  
Output any valid partition: first K, then for each city its province index (1…K), then the list of K capitals. If impossible, output 0.

2. Key Observations  
- Since the graph is a tree, rooting it (say at node 1) gives a parent–child structure and unique paths.  
- The reachability rule implies that the capital of a province can be chosen as the highest (closest to the root) node in that province: all members then ascend through ancestors within the province until they reach the capital.  
- We can build provinces in a single post-order DFS by grouping subtrees once we have collected ≥B unassigned nodes.  
- By always cutting exactly the accumulated unassigned batch of size in [B,2B–1], we ensure no province exceeds 3B in size, even after absorbing leftover nodes (<B) into the last province.

3. Full Solution Approach  
a. Root the tree at node 1.  
b. Maintain during DFS:  
   • A global stack `st` of nodes in the current subtree not yet assigned to any province.  
   • A list `capitals` of chosen capital cities (1-based).  
   • An array `comp[1…N]` to record each node’s province index.  
c. Define `dfs(u,parent)` that returns the count of unassigned nodes in u’s subtree after processing. Inside it:  
   1. Initialize `cnt_here = 0`.  
   2. For each child v of u:  
      - Recurse: `cnt_here += dfs(v,u)`.  
      - If `cnt_here >= B`, form a new province rooted at u:  
         · Append capital `u` to `capitals`.  
         · Let `pid = size of capitals` (new province index).  
         · Pop exactly `cnt_here` nodes from `st`, assign them `comp[node] = pid`.  
         · Reset `cnt_here = 0`.  
   3. After children, push `u` onto `st` (it remains unassigned for now), and return `cnt_here + 1`.  
d. Call `dfs(1,0)`.  
e. If no province was ever formed, force one with capital = 1.  
f. Any nodes left in `st` (<B of them) join the last province: pop them and assign `comp[node] = last_pid`.  
g. Output:  
   - K = number of capitals.  
   - The array `comp[1…N]`.  
   - The list `capitals` (converted to 1-based indices).  

Correctness and bounds:  
- Each cut takes a batch of size between B and 2B–1 (because we cut immediately once we reach ≥B, and after reset we can only accumulate at most B–1 more before the next cut).  
- The final leftover (<B) merges into a batch of size ≤(2B–1)+(B–1)=3B–2 ≤3B.  
- Each province is connected and satisfies the capital reachability rule by construction.  
- Time complexity O(N); each node is pushed/popped at most once.

4. C++ Implementation with Detailed Comments  
```cpp
#include <bits/stdc++.h>
using namespace std;

// Globals
int N, B;
vector<vector<int>> adj;  // adjacency list
vector<int> comp;         // comp[i] = province index of city i (0-based)
vector<int> capitals;     // list of capitals (1-based)
vector<int> st;           // stack of unassigned nodes

// DFS returns the count of currently unassigned nodes in u's subtree
int dfs(int u, int parent) {
    int cnt_here = 0;
    // Process all children in post-order
    for (int v : adj[u]) {
        if (v == parent) continue;
        cnt_here += dfs(v, u);
        // Once we have at least B unassigned, cut them out as a province
        if (cnt_here >= B) {
            // New province with capital u+1
            capitals.push_back(u + 1);
            int pid = (int)capitals.size();  // new province index (1-based)
            // Pop exactly cnt_here nodes from stack, assign them to province pid
            while (cnt_here > 0) {
                int node = st.back();
                st.pop_back();
                comp[node] = pid;
                --cnt_here;
            }
            // cnt_here resets to 0 implicitly
        }
    }
    // After handling children, u itself is still unassigned
    st.push_back(u);
    // Return count of unassigned in this subtree including u
    return (cnt_here + 1);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    // Read input
    cin >> N >> B;
    adj.assign(N, {});
    for (int i = 0; i < N-1; i++) {
        int u, v;
        cin >> u >> v;
        --u; --v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    comp.assign(N, 0);
    // Run DFS from root = 0
    dfs(0, -1);

    // If no province was formed, create one with capital = 1
    if (capitals.empty()) {
        capitals.push_back(1);
    }
    int last_pid = (int)capitals.size();
    // Assign any leftover nodes (<B of them) to the last province
    while (!st.empty()) {
        int node = st.back(); st.pop_back();
        comp[node] = last_pid;
    }

    // Output results
    cout << capitals.size() << "\n";
    for (int i = 0; i < N; i++) {
        cout << comp[i] << (i+1<N? ' ' : '\n');
    }
    for (int i = 0; i < (int)capitals.size(); i++) {
        cout << capitals[i] << (i+1<(int)capitals.size()? ' ' : '\n');
    }
    return 0;
}
```

5. Python Implementation with Detailed Comments  
```python
import sys
sys.setrecursionlimit(20000)

def main():
    data = sys.stdin.read().split()
    it = iter(data)
    n, B = int(next(it)), int(next(it))

    # Build adjacency list
    adj = [[] for _ in range(n)]
    for _ in range(n-1):
        u, v = int(next(it))-1, int(next(it))-1
        adj[u].append(v)
        adj[v].append(u)

    comp = [0]*n         # province index for each node
    capitals = []        # list of capitals (1-based)
    st = []              # stack of unassigned nodes

    def dfs(u, parent):
        cnt_here = 0
        # Post-order traversal
        for v in adj[u]:
            if v == parent:
                continue
            cnt_here += dfs(v, u)
            # If we have gathered ≥B, cut them here
            if cnt_here >= B:
                capitals.append(u+1)      # record capital
                pid = len(capitals)       # new province index
                for _ in range(cnt_here):
                    x = st.pop()
                    comp[x] = pid
                cnt_here = 0
        # After children, push u itself as unassigned
        st.append(u)
        return cnt_here + 1

    # Run DFS from root 0
    dfs(0, -1)

    # If no province formed, force one
    if not capitals:
        capitals.append(1)
    last_pid = len(capitals)
    # Assign leftovers (<B) to the last province
    while st:
        comp[st.pop()] = last_pid

    # Output
    print(last_pid)
    print(" ".join(map(str, comp)))
    print(" ".join(map(str, capitals)))

if __name__ == "__main__":
    main()
```

Explanation of Key Steps:  
- We cut off a new province whenever the accumulated unassigned count `cnt_here` at a node u reaches B. This guarantees each province has at least B nodes.  
- Because after each cut we reset the local counter to 0, the next batch can grow at most to B–1 before possibly cutting again, ensuring no cut produces more than 2B–1 nodes.  
- Finally, we merge any remaining (<B) nodes into the last province. Since that province already had at most 2B–1 nodes, the merged result has size ≤3B–2.  
- Connectivity and the reachability rule follow from always choosing the current node u as capital when cutting at u.