1. 程式人生 > >CCF 201503-04 網絡延時

CCF 201503-04 網絡延時

pac 深度 algorithm oid ack ons 遍歷樹 spa 最大

遍歷樹,獲取每個節點的深度。對每個節點,考慮深度差最大的兩個子樹(即獲取到一個較大時延),以及子樹中最大的時延,比較得出最大。

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int N = 20015;
vector<int> tree[N];
#define getMax2Deep(a,b,c) (c>a?(b=a,a=c):((c>b)?(b=c):(1)))
int deep[N] = { 0 };
int n, m;
void buildTree() {
    int i = 2;
    int root;
    fill(deep, deep + N, 0);
    while (i<=n) {
        cin >> root;
        tree[root].push_back(i);
        i++;
    }
    while (i<=n + m) {
        cin >> root;
        tree[root].push_back(i);
        i++;
    }
}
int dfs(int root = 1) {//return max delay in this sub-tree
    int maxDelay = 0;
    int maxDeep = 0, max2deep = 0;
    if (tree[root].size() == 0) {
        deep[root] = 1;
        return 1;
    }
    for (int i = 0; i<tree[root].size(); i++) {
        maxDelay = max(maxDelay, dfs(tree[root][i]));
        getMax2Deep(maxDeep, max2deep, deep[tree[root][i]]);
    }
    deep[root] = maxDeep + 1;
    return max(maxDelay, maxDeep+max2deep);
}
int main() {
    freopen("in.txt", "r", stdin);
    cin >> n >> m;
    buildTree();
    cout << dfs();
    return 0;
}

CCF 201503-04 網絡延時