pku 2492 A Bug's Life
//方法1,思路更清晰
#include <stdio.h>
#include <string.h>
#define MAXN 2005
int father[MAXN],diff[MAXN];
int find(int x)
{
int i,t;
for(i=x; father[i]>0; i=father[i]) ;
while(x!=i)
{
t=father[x];
father[x]=i;
x=t;
}
return i;
}
int merge(int x,int y)
{
if(x==-1) return y;
if(y==-1) return x;
int fx=find(x),fy=find(y);
if(fx==fy) return fx;
if(father[fx]>father[fy])
{
father[fy]+=father[fx];
return father[fx]=fy;
}
else
{
father[fx]+=father[fy];
return father[fy]=fx;
}
}
inline void divide(int i,int j)
{
int fi=find(i),fj=find(j);
int x=merge(fi,diff[fj]);
int y=merge(diff[fi],fj);
//x,y都是根,diff[]总是对根进行处理
diff[x]=y;
diff[y]=x;
}
int main()
{
int T,cas;
scanf("%d",&T);
for(cas=1; cas<=T; cas++)
{
int N,M,i,j;
scanf("%d %d",&N,&M);
getchar();
memset(father,-1,sizeof(*father)*(N+1));
memset(diff,-1,sizeof(*diff)*(N+1));
bool ok=true;
while(M--)
{
scanf("%d %d",&i,&j);
if(find(i)==find(j)) ok=false;
if(ok) divide(i,j);
}
if(cas>1) printf("\n");
printf("Scenario #%d:\n",cas);
if(ok) printf("No suspicious bugs found!\n");
else printf("Suspicious bugs found!\n");
}
return 0;
}
//******************************************************************
//方法2:
#include <stdio.h>
#include <string.h>
#define MAXN 2001
int father[MAXN],oppo[MAXN];
int find(int x)
{
int i,t;
for(i=x; father[i]>0; i=father[i]) ;
while(x!=i)
{
t=father[x];
father[x]=i;
x=t;
}
return i;
}
void merge(int x,int y)
{
int fx=find(x),fy=find(y);
if(fx == fy) return;
// father[fy] = fx;
if( father[fx] > father[fy] )
{
father[fy] += father[fx];
father[fx] = fy;
}
else
{
father[fx] += father[fy];
father[fy] = fx;
}
}
int main()
{
int T,cas,n,m,i,j;
scanf("%d",&T);
for(cas=1; cas<=T; cas++)
{
scanf("%d %d",&n,&m);
memset(father,-1,sizeof(father));
memset(oppo,-1,sizeof(oppo));
bool ok=true;
while(m--)
{
scanf("%d %d",&i,&j);
if(find(i) == find(j)) ok=false;
if(ok)
{
if(oppo[i] == -1) oppo[i]=j;
else if(oppo[i] != j)
{
merge( oppo[i], j );
}
if(oppo[j] == -1) oppo[j]=i;
else if(oppo[j] != i)
{
merge( oppo[j] ,i );
}
}
}
if(cas>1) printf("\n");
printf("Scenario #%d:\n",cas);
if(ok) printf("No suspicious bugs found!\n");
else printf("Suspicious bugs found!\n");
}
return 0;
}