您的位置:首页 > Web前端

HDU 1829 A Bug's Life

2015-04-15 00:10 363 查看
题意:

给你一种生物的交配信息,n个虫子,m种交配对(比如1 2,就是编号1的和编号2的交配),让你判断这里面是否有同性恋的。

思路

首先明确,如果a与b交配,b与c交配,那么a和c就是同性,应该在一个集合里面,合并。

那么用一个数组来记录与a交配的虫子的编号。

对于a与b交配,看a和b是否在同一个集合中,如果在,则有同性恋,否则,就把与a交配的虫子和c放入同一个集合中。

Code:

#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cctype>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<stack>
#include<list>
#include<map>
#include<set>

#define TEST

#define Mt(f, x) memset(f, x, sizeof(f));
#define LL long long
#define rep(i, s, e) for(int i = (s); i <= (e); ++i)
#ifdef TEST
#define See(a) cout << #a << " = " << a << endl;
#define See2(a, b) cout << #a << " = " << a << ' ' << #b << " = " << b << endl;
#define debug(a, s, e) rep(_i, s, e) {cout << a[_i] << ' ';} cout << endl;
#define debug2(a, s, e, ss, ee) rep(i_, s, e) {debug(a[i_], ss, ee);}
#else
#define See(a)
#define See2(a, b)
#define debug(a, s, e)
#define debug(a, s, e, ss, ee)
#endif // TEST

const int MAX = 2e9;
const int MIN = -2e9;
const double eps = 1e-8;
const double pi = acos(-1.0);

using namespace std;

const int N = 2005;

int uf
, note
;//uf实现并查集,note[i]记录与i交配的虫子的编号。
int n, m;

void init()
{
for(int i = 1; i <= n; ++i)
{
uf[i] = i;
}
Mt(note, 0);
}

int fd(int n)
{
if(uf
!= n)
uf
= fd(uf
);
return uf
;
}

void mer(int a, int b)
{
int f1 = fd(a);
int f2 = fd(b);
if(f1 != f2)
{
uf[f1] = f2;
}
}

int main()
{
int T;
cin >> T;
for(int _ = 1; _ <= T; ++_)
{
scanf("%d%d", &n, &m);
init();
bool ans = false;
for(int i = 0; i < m; ++i)
{
int a, b;
scanf("%d%d", &a, &b);
if(ans)
continue;
if(fd(a) == fd(b))
{
ans = true;
continue;
}
if(note[a] == 0)//note初始化为0
{
note[a] = b;
}
else
{
mer(note[a], b);
}
if(note[b] == 0)//记录两次因为交配关系是相互的
{
note[b] = a;
}
else
{
mer(note[b], a);
}
}
printf("Scenario #%d:\n", _);
printf("%s\n\n", ans ? "Suspicious bugs found!" : "No suspicious bugs found!");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: