【转】POJ 2492 A Bug's Life:基础并查集进阶
思路参考这里(较详细)
一开始总是WA调了一晚上原来···Init初始化写在scanf上面了···哎╮(╯▽╰)╭anyway!对并查集的理解更深了一步!
#include<cstdio> #include<cstring> using namespace std; #define Size 2000 struct node { int Pre; int Relation;// 与父节点的关系 0同性 1异性 }Bug[Size+1]; int N, M; bool found; void Init() { for( int i=1; i<=N; i++ ) { Bug[i].Relation = 0;// 自身与自身性别相同 Bug[i].Pre = i; } found = false; } int GetPre( int n ) { if( Bug[n].Pre == n ) return n; int t = GetPre( Bug[n].Pre ); Bug[n].Relation = Bug[n].Relation^Bug[Bug[n].Pre].Relation; Bug[n].Pre = t; return Bug[n].Pre; } void Union( int a, int b ) { int Pa = GetPre(a); int Pb = GetPre(b); if( Pa == Pb ){ if( Bug[a].Relation == Bug[b].Relation ) found = true; return; } Bug[Pa].Pre = Pb; Bug[Pa].Relation = ~(Bug[a].Relation^Bug[b].Relation); } int main() { int Snr; scanf("%d", &Snr); int i=1; for( i=1; i<=Snr; i++ ) { scanf("%d%d",&N, &M); Init(); while( M-- ) { int a, b; scanf("%d%d", &a, &b); if(!found) Union(a, b); } printf("Scenario #%d:\n",i); if( found ) printf("Suspicious bugs found!\n\n"); else printf("No suspicious bugs found!\n"); } return 0; }