結果

問題 No.1023 Cyclic Tour
ユーザー Mayimg
提出日時 2020-07-07 10:01:18
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 196 ms / 2,000 ms
コード長 1,828 bytes
コンパイル時間 3,087 ms
コンパイル使用メモリ 206,512 KB
最終ジャッジ日時 2025-01-11 16:39:59
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 49
権限があれば一括ダウンロードができます

ソースコード

diff #

#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
/////////////////////////////////////////////////////////////////////////
// UNION FIND
/////////////////////////////////////////////////////////////////////////
class UnionFind {
private:
  int siz;
  vector<int> a;

public:
  UnionFind(int x) : siz(x), a(x, -1) {}

  int root(int x) {
    return a[x] < 0 ? x : a[x] = root(a[x]);
  }

  bool unite(int x, int y) {
    x = root(x);
    y = root(y);
    if (x == y) return false;
    siz--;
    if (a[x] > a[y]) swap(x, y);
    a[x] += a[y];
    a[y] =x;
    return true;
  }

  bool same(int x, int y) {
    return root(x) == root(y);
  }

  int size(int x) {
    return -a[root(x)];
  }
  
  int connected_component() {
  	return siz;
  }
};
/////////////////////////////////////////////////////////////////////////
// END UNION FIND
/////////////////////////////////////////////////////////////////////////

vector<set<int>> g;
vector<int> vis;

void dfs (int cur) {
  if (vis[cur] == 2) return;
  if (vis[cur] == 1) {
    cout << "Yes" << endl;
    exit(0);
  }
  vis[cur] = 1;
  for (int nxt : g[cur]) {
    dfs(nxt);
  }
  vis[cur] = 2;
}

signed main() { 
  ios::sync_with_stdio(false); cin.tie(0);
  int n, m;
  cin >> n >> m;
  vector<pair<int, int>> de;
  UnionFind uf(n);
  for (int i = 0; i < m; i++) {
    int u, v, t;
    cin >> u >> v >> t;
    u--;
    v--;
    if (t == 1) {
      if (!uf.unite(u, v)) {
        cout << "Yes" << endl;
        return 0;
      }
    } else {
      de.emplace_back(u, v);
    }
  }
  g = vector<set<int>>(n);
  vis = vector<int>(n);
  for (auto& p : de) {
    p.first = uf.root(p.first);
    p.second = uf.root(p.second);
    g[p.first].insert(p.second);
  }
  for (int i = 0; i < n; i++) {
    if (!vis[i]) dfs(i);
  }
  cout << "No" << endl;
  return 0;
}
0