結果

問題 No.1023 Cyclic Tour
ユーザー chocorusk
提出日時 2020-02-28 14:47:12
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 157 ms / 2,000 ms
コード長 1,371 bytes
コンパイル時間 734 ms
コンパイル使用メモリ 75,756 KB
実行使用メモリ 15,616 KB
最終ジャッジ日時 2024-10-15 19:57:04
合計ジャッジ時間 8,647 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 49
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
struct unionfind{
    vector<int> par, sz;
    unionfind() {}
    unionfind(int n):par(n), sz(n, 1){
        for(int i=0; i<n; i++) par[i]=i;
    }
    int find(int x){
        if(par[x]==x) return x;
        return par[x]=find(par[x]);
    }
    void unite(int x, int y){
        x=find(x); y=find(y);
        if(x==y) return;
        if(sz[x]>sz[y]) swap(x, y);
        par[x]=y;
        sz[y]+=sz[x];
    }
    bool same(int x, int y){
        return find(x)==find(y);
    }
    int size(int x){
        return sz[find(x)];
    }
};
int n, m;
int a[200020], b[200020], c[200020];
vector<int> g[100010];
bool used[100010];
bool finish[100010];
bool ok;
void dfs(int x){
	used[x]=1;
	for(auto y:g[x]){
		if(used[y] && !finish[y]) ok=1;
		if(!used[y]) dfs(y);
	}
	finish[x]=1;
}
int main()
{
    cin>>n>>m;
	for(int i=0; i<m; i++){
		cin>>a[i]>>b[i]>>c[i];
		a[i]--; b[i]--;
	}
	unionfind uf(n);
	for(int i=0; i<m; i++){
		if(c[i]==1){
			if(uf.same(a[i], b[i])){
				cout<<"Yes"<<endl;
				return 0;
			}
			uf.unite(a[i], b[i]);
		}
	}
	for(int i=0; i<m; i++){
		if(c[i]==2) g[uf.find(a[i])].push_back(uf.find(b[i]));
	}
	for(int i=0; i<n; i++){
		if(used[i]) continue;
		dfs(i);
		if(ok){
			cout<<"Yes"<<endl;
			return 0;
		}
	}
	cout<<"No"<<endl;
    return 0;
}
0