You are my brother (并查集之变形——查找步数)

来源:互联网 发布:网络维护明细 编辑:程序博客网 时间:2024/05/21 06:36

You are my brother

Time limit  1000 ms             Memory limit      131072 kB

Little A gets to know a new friend, Little B, recently. One day, they realize that they are family 500 years ago. Now, Little A wants to know whether Little B is his elder, younger or brother.
Input
There are multiple test cases.
For each test case, the first line has a single integer, n (n<=1000). The next n lines have two integers a and b (1<=a,b<=2000) each, indicating b is the father of a. One person has exactly one father, of course. Little A is numbered 1 and Little B is numbered 2.
Proceed to the end of file.
Output
For each test case, if Little B is Little A’s younger, print “You are my younger”. Otherwise, if Little B is Little A’s elder, print “You are my elder”. Otherwise, print “You are my brother”. The output for each test case occupied exactly one line.
Sample Input
51 32 43 54 65 661 32 43 54 65 76 7
Sample Output
You are my elderYou are my brother


题解:题意就是1和2想知道谁大,给你一个n,然后n行b,c。表示b的父亲是c……

简单的并查集,找之间节点的个数……


#include<stdio.h>#include<iostream>#include<algorithm>#include<string.h>#include<stdlib.h>#include<time.h>#include<string>#include<math.h>#include<map>#include<queue>#include<stack>#define INF 0x3f3f3f3f#define ll long long#define For(i,a,b) for(int i=a;i<b;i++)#define sf(a)  scanf("%d",&a)#define sff(a,b)  scanf("%d%d",&a,&b)#define pf(a) printf("%d\n",a)#define mem(a,b) memset(a,b,sizeof(a))using namespace std;int pre[2005];int find(int x)          // 找节点的个数{    int s=0;    while(pre[x]!=x)    {        s++;        if(pre[x]==1||pre[x]==2)break;    // 提前跳出,节省时间        x=pre[x];    }    return s;}int main(){    int n;    while(~sf(n))    {        mem(pre,0);        int a,b;        For(i,0,n)        {            sff(a,b);            pre[a]=b;        }        int aa=find(1);        int bb=find(2);        if(aa>bb)            printf("You are my elder\n");        else if(aa==bb)            printf("You are my brother\n");        else printf("You are my younger\n");    }}


0 0
原创粉丝点击