PTA1021 Deepest Root (25分)

題目click me~

題意:給n個點,n-1條邊,判斷是否連通圖。

若是,找出能使樹高最高的根結點(如果這樣的結點不止一個,那麼升序輸出它們);

若不是,輸出連通塊個數。

解題思路

步驟一:判斷是否連通圖;

步驟二:先任意選擇一個結點開始遍歷樹,獲取能達到的最深的頂點(記爲A集合)。若是連通圖,再從A中任選擇一個結點出發遍歷樹,獲取能達到的最深的頂點(記爲B集合),那麼A、B的並集即爲所求的deepest root。

Tips:

1.標誌一個visit數組,每次dfs時,都把訪問到的結點visit【i】置爲1,用循環遍歷所有結點,沒有visit的結點再進行dfs,連通塊個數++。

2.STL中的set自動排序、去重,可以直接存放deepest root。

code:

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
int n, maxheight = 0;
vector<vector<int>> v;
bool visit[10010];
set<int> s;
vector<int> temp;
void dfs(int node, int height) {
    if(height > maxheight) {
        temp.clear();
        temp.push_back(node);
        maxheight = height;
    } else if(height == maxheight){
        temp.push_back(node);
    }
    visit[node] = true;
    for(int i = 0; i < v[node].size(); i++) {
        if(visit[v[node][i]] == false)
            dfs(v[node][i], height + 1);
    }
}
int main() {
    scanf("%d", &n);
    v.resize(n + 1);
    int a, b, cnt = 0, s1 = 0;
    for(int i = 0; i < n - 1; i++) {
        scanf("%d%d", &a, &b);
        v[a].push_back(b);
        v[b].push_back(a);
    }
    for(int i = 1; i <= n; i++) {
        if(visit[i] == false) {
            dfs(i, 1);
            if(i == 1) {
                if (temp.size() != 0) s1 = temp[0];
                for(int j = 0; j < temp.size(); j++)
                    s.insert(temp[j]);
            }
            cnt++;
        }
    }
    if(cnt >= 2) {
        printf("Error: %d components", cnt);
    } else {
        temp.clear();
        maxheight = 0;
        fill(visit, visit + 10010, false);
        dfs(s1, 1);
        for(int i = 0; i < temp.size(); i++)
            s.insert(temp[i]);
        for(auto it = s.begin(); it != s.end(); it++)
            printf("%d\n", *it);
    }
    return 0;
}

 

 

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