您的位置:首页 > 其它

HLJUOJ1002(并查集变形求结点高度)

2014-11-21 20:03 134 查看

1002: You are my brother

Time Limit: 1 Sec Memory Limit:
128 MB

Submit: 33 Solved: 16

[Submit][Status][Web Board]

Description

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向上回溯并记录高度,最后高度作比较即可

完整代码:
#include <functional>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cstring>
#include <climits>
#include <cassert>
#include <complex>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>
using namespace std;

#pragma comment(linker, "/STACK:102400000,102400000")

typedef long long LL;
typedef double DB;
typedef unsigned uint;
typedef unsigned long long uLL;

/** Constant List .. **/ //{

const int MOD = int(1e9)+7;
const int INF = 0x3f3f3f3f;
const LL INFF = 0x3f3f3f3f3f3f3f3fLL;
const DB EPS = 1e-9;
const DB OO = 1e20;
const DB PI = acos(-1.0); //M_PI;
const int maxn= 100001;
int f[maxn];

void init()
{
    for(int i = 0 ; i < maxn ; i ++)
        f[i] = i;
}

int main()
{
    #ifdef DoubleQ
    freopen("in.txt","r",stdin);
    #endif
    int n;
    while(~scanf("%d",&n))
    {
        init();
        for(int i = 0 ; i < n ; i ++)
        {
            int a , b;
            scanf("%d%d",&a,&b);
            f[a] = b;
        }
        int cnt1 = 0 , cnt2 = 0;
        int k1 = 1 , k2 = 2;
        while(k1 != f[k1])
        {
            cnt1 ++;
            k1 = f[k1];
        }
        while(k2 != f[k2])
        {
            cnt2 ++;
            k2 = f[k2];
        }
        if(cnt1 > cnt2)
        {
            printf("You are my elder\n");
        }
        else if(cnt1 < cnt2)
        {
            printf("You are my younger\n");
        }
        else
            printf("You are my brother\n");
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: