POJ 2492 并查集

来源:互联网 发布:代理模式java例子 编辑:程序博客网 时间:2024/05/21 06:55

题意:调查一种虫子的性行为,先假定虫子里没有同性恋。每一次测试输入N只虫,然后输入M个数对( x, y ),表示 x, y 之间有性行为, 最后判断假设成立与否(即判断有没有同性恋)。

#include <iostream>using namespace std;#define N 1000005int opp[N], father[N], rank[N];void make_set ( int x ){for ( int i = 0; i <= x; ++i ){father[i] = i;opp[i] = rank[i] = 0;}}int find_set ( int x ){if ( father[x] != x )father[x] = find_set(father[x]);return father[x];}void Union ( int x, int y ){int fx = find_set(x);int fy = find_set(y);if ( fx == fy ) return;if ( rank[fx] > rank[fy] )father[fy] = fx;elsefather[fx] = fy;if ( rank[fx] == rank[fy] )rank[fy]++;}int main(){int t, n, m, x, y;bool find;scanf("%d",&t);for ( int i = 1; i <= t; ++i ){find = false;scanf("%d%d",&n,&m);make_set(n);while ( m-- ){scanf("%d%d",&x,&y);if ( find == false ){if ( opp[x] == 0 && opp[y] == 0 ){opp[x] = y;opp[y] = x;}else if ( opp[x] != 0 && opp[y] == 0 ){opp[y] = x;Union(y,opp[x]);}else if ( opp[x] == 0 && opp[y] != 0 ){opp[x] = y;Union(x,opp[y]);}else if ( opp[x] != 0 && opp[y] != 0 ){if ( find_set(x) == find_set(y) )find = true;Union(x,opp[y]);Union(y,opp[x]);}}}printf("Scenario #%d:\n",i);if ( find )printf("Suspicious bugs found!\n");elseprintf("No suspicious bugs found!\n");if ( i != t ) putchar('\n');}return 0;}


原创粉丝点击