1. 程式人生 > >poj 2492 A Bug's Life

poj 2492 A Bug's Life

void string while math isp pla 關系 tmp clu

帶權並查集模2系,也就是給一些關系 ,這些關系是是否同類。問有多少關系錯的。

技術分享圖片
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int M = 2e3+7;
int _,n,m,cas=1;
int f[M],cnt[M];
void init(){
    for(int i=0;i<=n;i++) f[i]=i,cnt[i]=0;
}
int find(int x){
    
if(x==f[x]) return x; int tmp=f[x]; f[x]=find(f[x]); cnt[x]=(cnt[x]+cnt[tmp])%2; return f[x]; } int main(){ freopen("1.in","r",stdin); freopen("1.out","w",stdout); scanf("%d",&_); while(_--){ scanf("%d%d",&n,&m); init(); int flg=1;
while(m--){ int u,v; scanf("%d%d",&u,&v); if(u<v) swap(u,v); int fu=find(u),fv=find(v); if(fu==fv){ if((cnt[u]-cnt[v]+2)%2!=1) flg=0; } else{ f[fu]=fv; cnt[fu]
=(cnt[v]-cnt[u]+1+2)%2; } } printf("Scenario #%d:\n",cas++); if(flg) printf("No suspicious bugs found!\n\n"); else printf("Suspicious bugs found!\n\n"); } return 0; }
View Code

poj 2492 A Bug's Life