问题描述:
样例输入:
样例输出:
正确的编译:(Accept)
#include <iostream>
using namespace std;
#define N 1000005
int opp[N], father[N], rank[N];
//opp记录那个他/她
void make_set ( int x )
{
for ( int i = 0; i <= x; ++i )
{
father[i] = i;
opp[i] = rank[i] = 0;
}
}
int find_set ( int x )
{
if ( father[x] != x )
father[x] = find_set(father[x]);
return father[x];
}
void Union ( int x, int y )
{
int fx = find_set(x);
int fy = find_set(y);
if ( fx == fy ) return;
if ( rank[fx] > rank[fy] )
father[fy] = fx;
else
father[fx] = fy;
if ( rank[fx] == rank[fy] )
rank[fy]++;
}
int main()
{
int t, n, m, x, y;
bool find;
scanf("%d",&t);
for ( int i = 1; i <= t; ++i )
{
find = false;
scanf("%d%d",&n,&m);
make_set(n);
while ( m-- )
{
scanf("%d%d",&x,&y);
if ( find == false )
{
if ( opp[x] == 0 && opp[y] == 0 )
{//如果x与y之前都没发生过性行为的话,然后x与y发生了,分别记录对方
opp[x] = y;
opp[y] = x;
}
else if ( opp[x] != 0 && opp[y] == 0 )
{//如果x不是初的话,但是y是初,
opp[y] = x;//记录对方
Union(y,opp[x]);//y与opp[x]应该是同一个性别,合并
}
else if ( opp[x] == 0 && opp[y] != 0 )
{//与上同理
opp[x] = y;
Union(x,opp[y]);
}
else if ( opp[x] != 0 && opp[y] != 0 )
{
if ( find_set(x) == find_set(y) )//当两个集合里面都有一样的虫子,那么就表示有同性恋
find = true;
Union(x,opp[y]);
Union(y,opp[x]);
}
}
}
printf("Scenario #%d:\n",i);
if ( find )
printf("Suspicious bugs found!\n");
else
printf("No suspicious bugs found!\n");
if ( i != t ) putchar('\n');
}
return 0;
}
自己编辑的,始终是wrong answer ,找不到愿因
#include <iostream>
#include <stdio.h>
#define N 2000000
using namespace std;
int father[N];
int rank[N];
int other[N];//开辟一个新的other数组,记录另一方
void init(int n)
{
for(int i=0;i<n;i++)
{
father[i]=i;
rank[i]=0;
other[i]=0;
}
}
int find_set(int x)
{
if(father[x]!=x)
father[x]=find_set(father[x]);
return father[x];
}
void unite(int x,int y)
{
int fx=find_set(x);
int fy=find_set(y);
if(fx==fy) return;
if(rank[fx]<rank[fy])
father[fx]=fy;
else
father[fy]=fx;
if (rank[fx]==rank[fy])
rank[fx]++;
}
int main()
{
int t,n,m,x,y;
bool flag;
scanf("%d",&t);
for(int i=1;i<=t;i++)
{
flag=false;
scanf("%d%d",&n,&m);
init(n);
while(m--)
{
scanf("%d%d",&x,&y);
if(flag==false)
{
if(other[x]==0&&other[y]==0)
{
other[x]=y;
other[y]=x;
}
else if(other[x]!=0&&other[y]==0)
{
other[y]=x;
unite(y,other[x]);
}
else if(other[x]==0&&other[y]!=0)
{
other[x]=y;
unite(x,other[y]);
}
else if(other[x]!=0&&other[y]!=0)
{
if (find_set(x)==find_set(y))
flag=true;
unite(x,other[y]);
unite(y,other[x]);
}
}
}
printf("Scenario #%d:\n",i);
if( flag )
printf("Suspicious bugs found!\n");
else
printf("No suspicious bugs found!\n");
if(i != t) printf("\n");
}
return 0;
}