<|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++ Solution
```cpp
#include <bits/stdc++.h>

using namespace std;

template<typename T1, typename T2>
ostream& operator<<(ostream& out, const pair<T1, T2>& x) {
    return out << x.first << ' ' << x.second;
}

template<typename T1, typename T2>
istream& operator>>(istream& in, pair<T1, T2>& x) {
    return in >> x.first >> x.second;
}

template<typename T>
istream& operator>>(istream& in, vector<T>& a) {
    for(auto& x: a) {
        in >> x;
    }
    return in;
};

template<typename T>
ostream& operator<<(ostream& out, const vector<T>& a) {
    for(auto x: a) {
        out << x << ' ';
    }
    return out;
};

int n, B;
vector<vector<int>> adj;

void read() {
    cin >> n >> B;
    adj.assign(n, {});
    for(int i = 1; i < n; i++) {
        int u, v;
        cin >> u >> v;
        u--, v--;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
}

int dfs(
    int u, int par, vector<int>& comp, vector<int>& capitals, vector<int>& st
) {
    int cnt_here = 0;
    for(int v: adj[u]) {
        if(v == par) {
            continue;
        }

        cnt_here += dfs(v, u, comp, capitals, st);
        if(cnt_here >= B) {
            capitals.push_back(u + 1);

            assert(cnt_here <= st.size());
            while(cnt_here) {
                comp[st.back()] = capitals.size();
                st.pop_back();
                cnt_here--;
            }
        }
    }

    st.push_back(u);
    cnt_here++;
    return cnt_here;
}

void solve() {
    // We can solve this "recursively" after considering an arbitrary root.
    // In particular, let dfs(u) solve the problem for the subtree rooted at u
    // if we consider the overall root is 0. Let the "highest" component covered
    // be S. We can reuse a part of S, and then join it with other components at
    // par(u). Note that the capitals don't necessary have to be a part of S, so
    // we can join multiple children of par(u), and then simply use capital(s) =
    // par(u). We have the constraint that each group should have size within
    // [B; 3 * B]. We can always cut the components (e.g. S) when it reaches
    // size >= B, and this guarantees the above. One thing we should be careful about
    // is to make sure the final component in subree(u) is connected, before joining
    // with the other children of par(u). One way to do this is by having a post-order
    // of the tree.

    vector<int> capitals, st;
    vector<int> comp(n);

    dfs(0, 0, comp, capitals, st);

    if(capitals.empty()) {
        capitals.push_back(1);
    }

    while(!st.empty()) {
        comp[st.back()] = capitals.size();
        st.pop_back();
    }

    cout << capitals.size() << endl;
    cout << comp << endl;
    cout << capitals << endl;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int T = 1;
    // cin >> T;
    for(int test = 1; test <= T; test++) {
        read();
        // cout << "Case #" << test << ": ";
        solve();
    }

    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.