【並查集】【Rqnoj331】家族_input

來源:互聯網
上載者:User
題目描述若某個家族人員過於龐大,要判斷兩個是否是親戚,確實還很不容易,現在給出某個親戚關係圖,求任意給出的兩個人是否具有親戚關係。 規定:x和y是親戚,y和z是親戚,那麼x和z也是親戚。 如果x,y是親戚,那麼x的親戚都是y的親戚,y的親戚也都是x的親戚。 輸入格式第一行:三個整數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是否具有親戚關係。輸出格式P行,每行一個'Yes'或'No'。表示第i個詢問的答案為“具有”或“不具有”親戚關係。
Sample Input6 5 31 21 53 45 21 31 42 35 6

SampleOutputYesYesNo

#include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <ctime>#include <cmath>#define mxn 5000+10#define locusing namespace std;int n,m,p;int f[mxn];int fd(int x){    if (f[x]==x) return x;    f[x]=fd(f[x]);    return f[x];}int mrg(int x,int y){    int rx=fd(x),ry=fd(y);    f[rx]=f[ry];}int main(){    #ifdef loc    freopen("family.in","r",stdin);    freopen("family.out","w",stdout);    #endif        scanf("%d%d%d",&n,&m,&p);        for (int i=1;i<=n;++i) f[i]=i;    int x,y;    for (int i=1;i<=m;++i)    {        scanf("%d%d",&x,&y);        mrg(x,y);            }        for (int i=1;i<=p;++i)    {        scanf("%d%d",&x,&y);        if (fd(x)==fd(y)) printf("Yes\n");        else printf("No\n");    }        return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.