iT邦幫忙

2021 iThome 鐵人賽

DAY 2
1

複習樹的特性,只要符合下面敘述,我們就會稱這個圖為樹:

O->O->O (根邊點邊點)

  • 圖上所有點是連通的,且沒有環,邊數是點數少一
  • 有一個根,從根到圖上每個點,都只有唯一一種路徑

 
 
 

題目的Input是

the first integer identifies the node from which the edge begins
the second integer identifies the node to which the edge is directed.

兩相隔的數字是點邊點的關係,每個case來的時候,會一直塞點邊點,直到0 0出現。
終止input是-1 -1

 
 
 

思路:

判斷是否有環,除了用adj矩陣配遍歷搜尋,還可以用並查集。
用並查集的話,速度比較快,但是輸入數字範圍只有說大於0,最後找了參考,知道要100000才過。

 
 
 

程式碼:

#include <iostream>
#define N 100000

using namespace std;

int used[N];
int arr[N];

int getroot(int);

int main() {
    int u, v, num = 1;
    
    while(cin >> u >> v) {
        if (u<0 || v<0) break;
        int isTree = 1;
        for (int i = 0; i < N; ++i) {
            arr[i] = i;
            used[i] = 0;
        }
        
        while(u!=0 && v!=0) {
            if (getroot(u) == getroot(v))
                isTree = 0;
            if (isTree) {
                used[u] = used[v] = 1;
                arr[getroot(v)] = getroot(u);
            }
            cin >> u >> v;
        }
        
        if (isTree){
            int flag = 0;
            for(int i = 0; i < N; ++i) {
                if (used[i] && getroot(i) == i) {
                    if (flag) {
                        isTree = 0;
                        break;
                    }
                    flag = 1;
                }
            }
        }
        
        if (isTree)
            cout << "Case " << num << " is a tree." << endl;
        else
            cout << "Case " << num << " is not a tree." << endl;
        num++;
    }

    return 0;
}

int getroot(int v) {
    if (arr[v]!=v){
        arr[v] = getroot(arr[v]);
    }
    return arr[v];
}

參考:
https://web.ntnu.edu.tw/~algo/Tree.html
https://blog.csdn.net/mobius_strip/article/details/39782475


上一篇
空虛的目錄
下一篇
Leetcode: 26. Remove Duplicates from Sorted Array
系列文
來解數學跟刷圖論跟幾何程式題或者我突然想研究的主題33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
阿瑜
iT邦研究生 4 級 ‧ 2021-09-17 16:25:04

好久不見的UVa/images/emoticon/emoticon07.gif

細枝 iT邦新手 4 級 ‧ 2021-09-17 21:37:23 檢舉

沒錯~

我要留言

立即登入留言