并查集
并查集 - yfmd - 博客园 (cnblogs.com)
xzy巨佬的博客
直接粘过来就是我的了
主要用于维护图的连通性,方便地检验冲突,防止自闭(网抑救星)等;
直接上个综合性比较强的例题
map+并查集
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<bits/stdc++.h> using namespace std; namespace _mzf { #define ll long long const ll N=1e6+100; ll n,cnt,t; map<ll,ll>f; struct node { ll x,y,e; }a[N]; ll flag; ll read() { ll sum=0,flag=1; char ch=getchar(); while(ch<'0'||ch>'9') { if(ch=='-') flag=-1; ch=getchar(); } while(ch>='0'&&ch<='9') { sum=sum*10+ch-'0'; ch=getchar(); } return flag*sum; } ll find(ll x) { if(f[x]!=x) f[x]=find(f[x]); return f[x]; } bool cmp(node a,node b) { return a.e>b.e; } void mzfmain() { t=read(); while(t--) { n=read(); f.clear(); flag=0; for(int i=1;i<=n;i++) { a[i].x=read(); a[i].y=read(); a[i].e=read(); f[a[i].x]=a[i].x; f[a[i].y]=a[i].y; } sort(a+1,a+1+n,cmp); for(int i=1;i<=n;i++) { ll s1=find(a[i].x),s2=find(a[i].y); if(a[i].e==1) f[s1]=s2; else if(s1==s2) { flag=1; cout<<"NO"<<endl; break; } } if(!flag) cout<<"YES"<<endl; } } } int main() { _mzf::mzfmain(); return 0; }
别忘了开O2(正解需要手动离散化)