hdu 1829 A Bug's Life
两种代码
1:
/*
以往的并查集题目是读入的是相同的,这和题目读入的是不同的
用set[]数组来判断
*/
#include"stdio.h"
#include"string.h"
int set[2010],v[2010];
int find(int x)
{
int r=x;
while(r!=set[r])
r=set[r];
return r;
}
void join(int x,int y)
{
int a,b;
a=find(x);b=find(y);
if(a<b) set[b]=a;
else set[a]=b;
}
int main()
{
int i,n,m,t,flag,cas,a,b;
scanf("%d",&t);
cas=1;
while(t--)
{
scanf("%d%d",&n,&m);
memset(v,0,sizeof(v));
flag=0;
for(i=1;i<=n;i++)
set[i]=i;
for(i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
if(flag)continue;
if(find(a)==find(b))
{
flag=1;continue;
}
else
{
if(v[a]==0) v[a]=b;//v[a]表示与a性别相反
else join(v[a],b);
if(v[b]==0) v[b]=a;
else join(v[b],a);
}
}
printf("Scenario #%d:\n",cas++);
if(flag)
printf("Suspicious bugs found!\n");
else
printf("No suspicious bugs found!\n");
printf("\n");
}
return 0;
}
:2:
#include <iostream>
using namespace std;
int n,r;
//don't use set and sex next time. it is easy to confuse them.
int set[2002];//store the root
bool sex[2002];//store the relationship with the root. 1 means different sex, 0 mean same sex.
int find(int x)//find the root of x
{
if(set[x]==x)return x;//root is self
int t;
t=set[x];
set[x]=find(set[x]);//find the real root
sex[x]=(sex[x]+sex[t])%2;//compare the sex with root
//sex[x]is the relation between x and it's former root. sex[t] is the relation between the former root with the real root
//plus and remaind can get the relation between x and the real root
return set[x];
}
void merge(int x,int y)
{
int fx,fy;
fx=find(x);
fy=find(y);
set[fx]=fy;//put x into y
sex[fx]=(sex[x]+sex[y]+1)%2;
//x compare to its root, y compare to its root. 1 means x and y are different sex.
//plus and remaind so we get fx compare to fy
}
int main()
{
int cas;
cin>>cas;
int ci=0;
int x,y;//temp
while(cas--)
{
ci++;
int i;
int flag=0;//0 means no suspicious
scanf("%d%d",&n,&r);//number of bug, relation
for(i=0;i<n;i++)//it is n,not r...
{
set[i]=i;//everybug's root is it self
sex[i]=0;
}
while(r--)//it is r,not n...
{
scanf("%d%d",&x,&y);
if(find(x)==find(y))
//have the same root, which means they can be compared
{
if(sex[x]==sex[y])//sex is the same
flag=1;
}
else
merge(x,y);//merge them into one root
// because the data is simple, so we just simply put x into y. no need to worry about the height of x and y
}
printf("Scenario #%d:\n",ci);
if(flag)
printf("Suspicious bugs found!\n");
else
printf("No suspicious bugs found!\n");
printf("\n");
}
system("pause");
return 0;
}
浙公网安备 33010602011771号