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";
}
}
欢迎指教!!!