## implementation

DP。成分の個数を$2$進展開してまとめる。入力がグラフなのは適当にやる。$O(N \log N + M)$。

## solution

#include <iostream>
#include <vector>
#include <map>
#include <tuple>
#include <functional>
#define repeat(i,n) for (int i = 0; (i) < (n); ++(i))
#define repeat_from(i,m,n) for (int i = (m); (i) < (n); ++(i))
#define repeat_reverse(i,n) for (int i = (n)-1; (i) >= 0; --(i))
using namespace std;
template <class T> void setmin(T & a, T const & b) { if (b < a) a = b; }
const int inf = 1e9+7;
int main() {
// input
int n, m; cin >> n >> m;
vector<vector<int> > g(n);
repeat (i,m) {
int u, v; cin >> u >> v; -- u; -- v;
g[u].push_back(v);
g[v].push_back(u);
}
// enumerate components
map<int,int> components; {
vector<bool> used(n);
function<int (int)> go = [&](int i) {
used[i] = true;
int acc = 1;
for (int j : g[i]) if (not used[j]) acc += go(j);
return acc;
};
repeat (i,n) if (not used[i]) {
components[go(i)] += 1;
}
}
// dp
vector<int> dp(n+1, inf);
dp[0] = -1;
for (auto it : components) {
int size, cnt; tie(size, cnt) = it;
while (cnt) for (int k = 1; k <= cnt; cnt -= k, k *= 2) {
repeat_reverse (i,n+1-k*size) {
setmin(dp[i+k*size], dp[i]+k);
}
}
}
// output
repeat_from (i,1,n+1) {
cout << (dp[i] == inf ? -1 : dp[i]) << endl;
}
return 0;
}