You are my brother(樹狀)

題目描述

 

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.c++

輸入

 

There are multiple test cases.spa

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.code

Proceed to the end of file.blog

輸出

 

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.ip

樣例輸入

5
1 3
2 4
3 5
4 6
5 6
6
1 3
2 4
3 5
4 6
5 7
6 7

樣例輸出

You are my elder
You are my brother

題意:1 和 2 有共同的祖先,尋找A 與 B 的關係 。輸入N對數,B 是 A 的父親。A 與 B 有三種關係 。 elder , younger , brother。

能夠把這道題當作一顆樹 , 共同祖先是根節點。比較 A 與 B 的樹深度 。

代碼一:
#include <bits/stdc++.h>
using namespace std;
int vis[3000];


int main()
{
    int n ;
    while(cin >> n)
    {
        memset(vis , 0 , sizeof(vis));
        for(int i = 0 ; i < n ; i++)
        {
            int u ,v ;
            cin >> u >> v ;
            vis[u] = v ; // 輸入造成樹狀。
        }
        int temp = 1 , a = 0;
        while(vis[temp] != 0)
        {
            temp = vis[temp] ; // 經過樹末往上延申
            a++ ;//記錄樹節點數
        }
        int tem = 2 , b = 0;
        while(vis[tem] != 0)
        {
            tem = vis[tem] ;
            b++;
        }
    //經過比較樹的節點深度來判斷A 與 B 的關係。
if(a > b) { cout << "You are my elder" << endl ; } else if(a < b) cout << "You are my younger" << endl ; else cout << "You are my brother" << endl ; } return 0; }

代碼二(並查)但我覺的沒怎麼體現並查ci

#include <bits/stdc++.h>
using namespace std;
int vis[3000];

void Find(int x , int &a)
{
    while(x != vis[x])
    {
        x = vis[x] ;
        a++;
    }

}


int main()
{
    int n ;
    while(cin >> n)
    {
        memset(vis , 0 , sizeof(vis));
        for(int i = 1 ; i <= 2000 ; i++)
            vis[i] = i ;
        for(int i = 0 ; i < n ; i++)
        {
            int u , v ;
            cin >> u >> v ;
            vis[u] = v ;
        }
        int a = 0 , b = 0 ;
        Find(1 , a);
        Find(2 , b);
        if(a > b)
                printf("You are my elder\n");
            else if(a < b)
                printf("You are my younger\n");
            else
                printf("You are my brother\n");


    }


    return 0;
}
相關文章
相關標籤/搜索