【题目链接】
http://poj.org/problem?id=2492
题目意思
给你一堆情侣的关系a和b。但是这些情侣关系可能冲突,也就是有同性恋的。现在问你给你n个人m个关系里面是否有同性恋(有则输出“Suspicious bugs found!”,没有输出“No suspicious bugs found!”),每个案例后面加个换行
解题思路
这题一开始就死扣带权值的并查集,如果是情侣关系权值一个0一个1;当在共同的时判断是否性别冲突。(由于粗心wa到哭o(╥﹏╥)o);后来发现可以直接用普通并查集做就可以了,由于不能确定谁是男谁是女,那么把两种情况都加入,也就是当a和b是情侣,那么设一个b+n为b相反性别(也就和a相同性别)加入a的集合,同理a+n和b加入一个集合。当a和a+n冲突时或b和b+n冲突就有同性恋。
代码部分
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <string>
#include <map>
using namespace std;
#define LL long long
#define inf 0x3f3f3f3
const int N = 2005;
int pre[N];
int val[N]; ///权值
int n,m;
bool fa;
void init()
{
for (int i = 0; i <= n; i++)
{
pre[i] = i;
val[i] = 0;
}
fa = true;
}
int fin(int x)
{
int k = pre[x];
if (x != pre[x])
{
pre[x] = fin(pre[x]);
val[x] = (val[k]+val[x])%2; ///修改权值
}
return pre[x];
}
void join(int x,int y)
{
int fx = fin(x);
int fy = fin(y);
if (fx == fy && (val[x]+val[y])%2 == 0) ///同性
fa = false;
else
{
pre[fx] = fy;
val[fx] = (val[y]+val[x]+1)%2; ///权值改为异性
}
}
int main()
{
int t,cas = 1;
scanf("%d",&t);
while (t--)
{
scanf("%d %d",&n,&m);
init();
for (int i = 0;i < m; i++)
{
int x,y;
scanf("%d %d",&x,&y);
join(x,y);
}
if (cas != 1)
printf("\n");
if (fa)
printf("Scenario #%d:\nNo suspicious bugs found!\n",cas++);
else
printf("Scenario #%d:\nSuspicious bugs found!\n",cas++);
}
return 0;
}
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <string>
#include <map>
using namespace std;
#define LL long long
#define inf 0x3f3f3f3
const int N = 4005;
int pre[N];
int n,m;
bool fa;
void init()
{
for (int i = 0; i <= 2*n; i++)
{
pre[i] = i;
}
fa = true;
}
int fin(int x)
{
if (x != pre[x])
pre[x] = fin(pre[x]);
return pre[x];
}
void join(int x,int y)
{
int fx = fin(x);
int fy = fin(y);
pre[fx] = fy;
}
int main()
{
int t,cas = 1;
scanf("%d",&t);
while (t--)
{
scanf("%d %d",&n,&m);
init();
for (int i = 0;i < m; i++)
{
int x,y;
scanf("%d %d",&x,&y);
join(x,y+n);
join(y,x+n);
if (fin(x) == fin(x+n) || fin(y) == fin(y+n))
fa = false;
}
if (cas != 1)
printf("\n");
if (fa)
printf("Scenario #%d:\nNo suspicious bugs found!\n",cas++);
else
printf("Scenario #%d:\nSuspicious bugs found!\n",cas++);
}
return 0;
}