結果
問題 | No.1023 Cyclic Tour |
ユーザー |
|
提出日時 | 2020-05-19 02:57:45 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 1,000 ms / 2,000 ms |
コード長 | 2,522 bytes |
コンパイル時間 | 2,218 ms |
コンパイル使用メモリ | 176,816 KB |
実行使用メモリ | 28,104 KB |
最終ジャッジ日時 | 2024-10-01 22:28:16 |
合計ジャッジ時間 | 20,077 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 4 |
other | AC * 49 |
ソースコード
#include <bits/stdc++.h>using namespace std;using ll = long long;using Graph = vector< vector<int> >;constexpr char newl = '\n';struct UnionFind {//各要素が属する集合の代表(根)を管理する//もし、要素xが根であればdata[x]は負の値を取り、-data[x]はxが属する集合の大きさに等しいvector<int> data;UnionFind(int sz) : data(sz, -1) {}bool unite(int x, int y) {x = find(x);y = find(y);bool is_union = (x != y);if (is_union) {if (data[x] > data[y]) swap(x, y);data[x] += data[y];data[y] = x;}return is_union;}int find(int x) {if (data[x] < 0) { //要素xが根であるreturn x;} else {data[x] = find(data[x]); //data[x]がxの属する集合の根でない場合、根になるよう更新されるreturn data[x];}}bool same(int x, int y) {return find(x) == find(y);}int size(int x) {return -data[find(x)];}};bool dfs(int cur, vector<int>& memo, const Graph& g, vector<int>& order) {memo[cur] = 1;for (int nex : g[cur]) {cerr << cur << " " << nex << newl;if (memo[nex] == 2) continue;if (memo[nex] == 1) return false;if (!dfs(nex, memo, g, order)) return false;}memo[cur] = 2;order.push_back(cur);return true;}bool tsort(const Graph& g, vector<int>& order) {vector<int> memo(g.size(), 0);for (int i = 0; i < g.size(); i++) {if (memo[i] != 0) continue;if (!dfs(i, memo, g, order)) return false;}reverse(order.begin(), order.end());return true;}int main() {cin.tie(nullptr);ios::sync_with_stdio(false);int n, m;cin >> n >> m;Graph g(n);UnionFind uf(n);for (int i = 0; i < m; i++) {int a, b, c;cin >> a >> b >> c;--a; --b;if (c == 1) {if (uf.same(a, b)) {cout << "Yes\n";return 0;}uf.unite(a, b);} else {g[a].push_back(b);}}Graph g2(n);for (int i = 0; i < n; i++) {int i2 = uf.find(i);for (int j : g[i]) {g2[i2].push_back(uf.find(j));}}vector<int> order;if (!tsort(g2, order)) {cout << "Yes\n";return 0;}cout << "No\n";return 0;}