結果
問題 | No.317 辺の追加 |
ユーザー |
![]() |
提出日時 | 2021-05-31 09:36:43 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 264 ms / 2,000 ms |
コード長 | 1,681 bytes |
コンパイル時間 | 2,236 ms |
コンパイル使用メモリ | 207,808 KB |
最終ジャッジ日時 | 2025-01-21 20:49:26 |
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 38 |
ソースコード
//https://ncode.syosetu.com/n4830bu/317/#include <bits/stdc++.h>using namespace std;struct UF {vector<int> data;UF(int n) : data(n, -1) {}int root(int k) {if (data[k] < 0)return k;return data[k] = root(data[k]);}bool unite(int x, int y) {x = root(x), y = root(y);if (x == y)return false;if (data[x] > data[y])swap(x, y);data[x] += data[y];data[y] = x;return true;}bool same(int x, int y) {return root(x) == root(y);}int size(int k) { return -data[root(k)]; }};int main() {int N, M;cin >> N >> M;UF uf(N);while (M--) {int u, v;cin >> u >> v;u--;v--;uf.unite(u, v);}map<int, int> mp;set<int> seen;for (int i = 0; i < N; i++) {int r = uf.root(i);if (!seen.count(r)) {seen.insert(r);mp[uf.size(r)]++;}}const int INF = 1e6;vector<int> dp(N + 1, INF);dp[0] = -1;for (auto [key, cnt] : mp) {auto update = [&](int n, int cost) {for (int i = N; i >= 0; i--) {int bef = i - n;if (bef < 0)return;dp[i] = min(dp[i], dp[bef] + cost);}};for (int i = 0;; i++) {int n = 1 << i;if (n > cnt)break;cnt -= n;update(n * key, n);}update(cnt * key, cnt);}for (int i = 1; i <= N; i++) {cout << (dp[i] == INF ? -1 : dp[i]) << endl;}}