You are my brother (並查集之變形——查找步數)

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
5
1 3
2 4
3 5
4 6
5 6
6
1 3
2 4
3 5
4 6
5 7
6 7
Sample Output
You are my elder
You 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");
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章