結果
問題 | No.1553 Lovely City |
ユーザー |
|
提出日時 | 2021-07-13 14:06:17 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 166 ms / 2,000 ms |
コード長 | 1,323 bytes |
コンパイル時間 | 1,095 ms |
コンパイル使用メモリ | 86,772 KB |
実行使用メモリ | 24,244 KB |
最終ジャッジ日時 | 2024-07-02 13:20:11 |
合計ジャッジ時間 | 10,436 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 26 |
ソースコード
#include <iostream>#include <algorithm>#include <vector>#include <queue>using namespace std;vector<int> v[200009];vector<pair<int, int> > r[200009], ans;int id[200009], ds[200009], p[200009];queue<int> q;int uf(int n){if (ds[n] == n) return n;return ds[n] = uf(ds[n]);}int main(){ios::sync_with_stdio(false);cin.tie(0);int n, m; cin >> n >> m;for (int i = 1; i <= n; i++)ds[i] = i;for (int i = 0; i < m; i++) {int a, b; cin >> a >> b;v[a].push_back(b);id[b]++;int ua = uf(a), ub = uf(b);if (ua != ub) ds[ua] = ub;}for (int i = 1; i <= n; i++)if (!id[i])q.push(i);int c = 0;while (!q.empty()) {int hn = q.front(); q.pop();c++; p[hn] = c;for (int i = 0; i < v[hn].size(); i++) {int tn = v[hn][i];id[tn]--;if (!id[tn]) q.push(tn);}}for (int i = 1; i <= n; i++)r[uf(i)].push_back(make_pair(p[i], i));for (int i = 1; i <= n; i++) {if (ds[i] != i) continue;sort(r[i].begin(), r[i].end());for (int j = 0; j + 1 < r[i].size(); j++)ans.push_back(make_pair(r[i][j].second, r[i][j + 1].second));if (!r[i][0].first)ans.push_back(make_pair(r[i].back().second, r[i][0].second));}cout << ans.size() << '\n';for (int i = 0; i < ans.size(); i++)cout << ans[i].first << " " << ans[i].second << '\n';return 0;}