【PAT甲级】1021. Deepest Root (25)

注:要考虑时间空间效率问题:使用邻接表,并减少使用dfs的次数(原来为n次dfs,后面改为2次)。
#include <stdio.h>
#include <string.h>
#include <deque>
#include <algorithm>
using namespace std;
int n;
deque<int> map[10001];
int set[10001];
void dfsTraverse(int t, int h, int &maxh, deque<int> &maxhIndex); 

int main(int argc, char *argv[]) {
    scanf("%d", &n);
    int i, j, k;
    int a, b;
    for(i = 0; i < n - 1; i++) {
        scanf("%d %d", &a, &b);
        map[a].push_back(b);
        map[b].push_back(a);
    }
    memset(set, -1, 10001 * sizeof(int));
    for (i = 1; i <= n; i++) {
        if (set[i] < 0 && !map[i].empty()) {
            for (j = 0; j < map[i].size(); j++) {
                int p = map[i][j];
                while (set[p] >= 0) p = set[p];
                if (p != i) {
                    set[i] += set[p];
                    set[p] = i;
                }
            }
        }
    }//并查集
    int count = 0;
    for (i = 1; i <= n; i++) {
        if (set[i] < 0) count++;
    }
    if (count > 1) {
        printf("Error: %d components\n", count);
        return 0;
    }
    int maxDepth = 0;
    int depth = 0;
    deque<int> maxhIndex;
    maxhIndex.clear();
    memset(set, 0, 10001 * sizeof(int));
    dfsTraverse(1, 0, depth, maxhIndex); 
    int start = maxhIndex.front();
    deque<int> d(maxhIndex);
    memset(set, 0, 10001 * sizeof(int));
    maxhIndex.clear();
    dfsTraverse(start, 0, depth, maxhIndex);
    for (i = 0; i < d.size(); i++)
        maxhIndex.push_back(d[i]);
    sort(maxhIndex.begin(), maxhIndex.end());

    printf("%d\n", maxhIndex[0]);
    for (i = 1; i < maxhIndex.size(); i++)
        if (maxhIndex[i] != maxhIndex[i - 1])
            printf("%d\n", maxhIndex[i]);
    return 0;
}
void dfsTraverse(int t, int h, int &maxh, deque<int> &maxhIndex) {
    set[t] = 1;
    if (h > maxh) {
        maxh = h;
        maxhIndex.clear();
        maxhIndex.push_back(t);
    } else if (h == maxh) {
        maxhIndex.push_back(t);
    }
    for (int i = 0; i < map[t].size(); i++) {
        if (set[map[t][i]] == 0)
            dfsTraverse(map[t][i], h + 1, maxh, maxhIndex);
    }
    return;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值