并查集——1073 家族

来源:互联网 发布:人口数据泄露 编辑:程序博客网 时间:2024/05/17 21:34

1073 家族

时间限制: 1 s
空间限制: 128000 KB
题目等级 : 大师 Master

  • 题目描述 Description
    若某个家族人员过于庞大,要判断两个是否是亲戚,确实还很不容易,现在给出某个亲戚关系图,求任意给出的两个人是否具有亲戚关系。 规定:x和y是亲戚,y和z是亲戚,那么x和z也是亲戚。如果x,y是亲戚,那么x的亲戚都是y的亲戚,y的亲戚也都是x的亲戚。

  • 输入描述 Input Description
    第一行:三个整数n,m,p,(n<=5000,m<=5000,p<=5000),分别表示有n个人,m个亲戚关系,询问p对亲戚关系。 以下m行:每行两个数Mi,Mj,1<=Mi,Mj<=N,表示Ai和Bi具有亲戚关系。 接下来p行:每行两个数Pi,Pj,询问Pi和Pj是否具有亲戚关系。

  • 输出描述 Output Description
    P行,每行一个’Yes’或’No’。表示第i个询问的答案为“具有”或“不具有”亲戚关系。

  • 样例输入 Sample Input
    6 5 3
    1 2
    1 5
    3 4
    5 2
    1 3
    1 4
    2 3
    5 6

  • 样例输出 Sample Output
    Yes
    Yes
    No

  • 数据范围及提示 Data Size & Hint
    n<=5000,m<=5000,p<=5000

  • 分类标签 Tags
    并查集 树结构

#include<iostream>#include<queue>#include<cstdio>#include<algorithm>#include<cmath>#include<cstring>using namespace std;int f[1010],n,m,ans=0,d[1010];//d的引入int find(int x){    return (x==f[x]? x: f[x]=find(f[x]));}void he(int x,int y){    f[find(x)]=find(f[y]);}void csh(){    for(int i=1;i<=n;i++)        f[i]=i;}void in(){    cin>>n>>m;    csh();    for(int i=1;i<=m;i++)   {        char c;        int x,y;        cin>>c>>x>>y;        if(c=='F'){            //t[x][y]=t[y][x]=1;            he(x,y);                }            else  {                if(d[x]){                    he(d[x],y);                }                    else d[x]=y;                if(d[y]){                    he(d[y],x);                }                    else d[y]=x;            }//t[x][y]=t[y][x]=-1;    }} /*void c(){    for(int k=1;k<=n;k++)        for(int i=1;i<=n;i++)            for(int j=1;j<=n;j++){                if(t[i][k] && t[k][j] && i!=j ){                    t[i][j]=1;                    he(i,j);                }            }}*/int main(){    in();    //c();    for(int i=1;i<=n;i++)    {        if(f[i]==i){// i not n !!!!!!!!!            ans++;  //cout<<f[i]<<' '<<i<<endl;        }    }    cout<<ans;    return 0;}
0 0
原创粉丝点击