Relation

Relation


Time Limit:

2000MS

 
Memory Limit:

65535K

Description

对于任意的两个人,希望知道他们是否具有亲戚关系(即,他们属于同一个大家族)。你可以获得一些亲戚关系的信息,比如知道Peter和Paul是亲戚,Paul和Bush是亲戚,那么,能推断出Peter和Bush也是亲戚。

Input

首先输入整数N和M。 N表示有N个人(1≤N≤3000),人的编号为1,2,…,N。M表示接下来有M行(1≤M≤3000),每行有两个数s和t,表明s和t是亲戚关系。

然后输入整数P,表明下面有P行的询问(1≤P≤20000),每行有两个数y和z,询问y和z是否为亲戚。对于每次询问,若y和z是亲戚,输出YES,否则输出NO。

Output

每次询问对应一行输出。

Sample Input

10 7

2 4

5 7

1 3

8 9

1 2

5 6

2 3

3

3 4

7 10

8 9

Sample Output

YES

NO

YES

Hint

No hint.

Source


解题代码:

#include<iostream>
using namespace std;
int N,M,Q;
int pre[3000],rank[3000];
void makeset(int x)
 {
     pre[x]=-1;
     rank[x]=0;
 } 

int find(int x)
 {
     int r=x;
     while(pre[r]!=-1)
      r=pre[r];
     while(x!=r)
      {
          int q=pre[x];
          pre[x]=r;
          x=q;
      }
    return r;       
 }     

void unionone(int a,int b)
 {
     int t1=find(a);
     int t2=find(b);
     if(rank[t1]>rank[t2])
       pre[t2]=t1;
    else
       pre[t1]=t2;
    if(rank[t1]==rank[t2])
      rank[t2]++;      
 }        

int main()
{ 
  int i,a,b,c,d;
  cin>>N>>M;
         for(i=1;i<=N;i++)
          makeset(i);
        for(i=1;i<=M;i++)
          {
              cin>>a>>b;
              if(find(a)!=find(b))
               unionone(a,b);
          }

        cin>>Q;  
        for(i=1;i<=Q;i++)
         {
             cin>>c>>d;
             if(find(c)==find(d))
              cout<<"YES"<<endl;
             else
              cout<<"NO"<<endl;  
         }            
   

} 

参考资料:

http://blog.csdn.net/fandywang_jlu/article/details/2201347


我的解法:

#include <iostream>
using namespace std;
int find(int *&A,int a,int b)
{
	if(A[a]==A[b])
		if(A[a]==-1)
			return 0;
		else
			return 1;
	else
		return 2;
}

void unite(int *&A,int a,int b,int& i,int t,int n)
{
	if(t==0)
	{
		A[a]=i;
		A[b]=i++;
	}
	else if(t==2)
	{
		if(A[a]==-1)
		{
			A[a]=A[b];
			return;
		}
		else if(A[b]==-1)
		{
			A[b]=A[a];
			return;
		}

		int up,low;
		if(A[a]>A[b])
		{up=A[a];low=A[b];}
		else
		{up=A[b];low=A[a];}
		//取较小的值作为标记
		for(int j=0;j<n;j++)
			if(A[j]==up)
				A[j]=low;
	}
}

int main()
{
	int n,m;
	int a,b;;
	int i=0;
	cin>>n>>m;
	int *A=new int[n++];
	for(int j=0;j<n;j++)
		A[j]=-1;
	while(m>0)
	{
		cin>>a>>b;
       unite(A,a,b,i,find(A,a,b),n);
	   m--;
	}

	cin>>n;
	while(n-->0)
	{
		cin>>a>>b;
		if(find(A,a,b)==1)
			cout<<"YES\n";
		else
			cout<<"NO\n";
	}
}


欢迎指教!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值