这两天在处理这类题目,经过两三道题,差不多也理解该怎么做了,接下来就是熟练了。
题目描述
题目:https://vjudge.net/problem/POJ-2492
大概意思就是:
有几只bug,题目告诉你哪两只在相互交往,判断这些bug是否有同性恋。
输入:
先是样样例
每个样例开头一行两个数n m,n为虫子数,m为提供的关系数
输出就看样例把。
思路分析
这道题因为涉及到虫子和虫子之间的关系,所以我们想到了并查集。而且,由于关系之间还是有区别的(同性和异性),所以这是一道带权并查集。
说到带权并查集,每个节点要记录的就是就有两点:父节点和与父节点的关系。有些大佬用多个数组表示,渣渣表示模仿不来,还是结构体来的方便。
struct node{
int parent;
int relation;
}a[2050];
这里relation分为两个值:0为与父节点为同性,1为异性。
初始化函数比较简单,就令a[i]=i,relation都为0就行了。
接下来是find函数,这里涉及到压缩路径和重新确定关系的算法。这里主要讲重新确定关系。这里我们采用递归的思想压缩路径:
对于左边这种情况:X的relation为a。
对于右边这种情况:需要设置的就是X和R之间的relation,也就是c,通过列表,我们发现:
a b c
1 1 0
1 0 1
0 1 1
0 0 0
于是得到:c=(a+b)%2的关系。
因此:
int find_set(int x)
{
if(a[x].parent==x) return x;
else
{
int t=a[x].parent;
a[x].parent=find_set(a[x].parent);
a[x].relation=(a[x].relation+a[t].relation)%2;
}
return a[x].parent;
}
对于合并集合的函数,难点依旧是重新确定关系:
按照刚才的方法一句可以得到关系:
d=(a+c+1)%2
这样可以写成组合函数:
void union_set(int x,int y)
{
int r1=find_set(x);
int r2=find_set(y);
if(r1==r2)
{
if((a[x].relation==a[y].relation)) counter++;
}
else
{
a[r2].parent=r1;
a[r2].relation=(1+a[x].relation+a[y].relation)%2;
}
}
剩下的就是输出的小问题了,这里就不说了。
注:每次输出之后要多一个空行。
完整代码
#include <iostream>
#include <cstdio>
using namespace std;
struct node{
int parent;
int relation;
}a[2050];
int counter=0;
void init(int n)
{
for(int i=1;i<=n;i++)
{
a[i].parent=i;
a[i].relation=0;
}
}
int find_set(int x)
{
if(a[x].parent==x) return x;
else
{
int t=a[x].parent;
a[x].parent=find_set(a[x].parent);
a[x].relation=(a[x].relation+a[t].relation)%2;
}
return a[x].parent;
}
void union_set(int x,int y)
{
int r1=find_set(x);
int r2=find_set(y);
if(r1==r2)
{
if((a[x].relation==a[y].relation)) counter++;
}
else
{
a[r2].parent=r1;
a[r2].relation=(1+a[x].relation+a[y].relation)%2;
}
}
int main()
{
// freopen("in.txt","r",stdin);
int n;
scanf("%d",&n);
int kase=0;
while(n--)
{
printf("Scenario #%d:\n",++kase);
counter=0;
int num,re;
scanf("%d %d",&num,&re);
init(num);
while(re--)
{
int x,y;
scanf("%d %d",&x,&y);
union_set(x,y);
}
if(counter==0)
{
printf("No suspicious bugs found!\n\n");
}
else
{
printf("Suspicious bugs found!\n\n");
}
}
return 0;
}