FZU 2195 检查站点

求出根节点到每个叶子节点的距离,找到最大的。然后总权值减去最大叶子距离就是答案。

GNU C++ AC

Visual C++  TLE

 

#include<stdio.h>

#include<vector>

#include<map>

#include<algorithm>

using namespace std;



const int maxn = 111111;

vector<int> ljb[maxn];

int cost[maxn], ff;



void dfs(int node, int fahther, int tot)

{

    if (tot > ff) ff = tot;

    int i;

    for (i = 0; i < ljb[node].size(); i++)

        dfs(ljb[node][i], node, tot + cost[ljb[node][i]]);

}

int main()

{

    int u, v, c, n, i;

    while (~scanf("%d", &n))

    {

        ff = 0;

        for (i = 0; i <= n; i++) ljb[i].clear();

        int summ = 0;

        cost[1] = 0; ljb[0].push_back(1);

        for (i = 0; i < n - 1; i++)

        {

            scanf("%d%d%d", &u, &v, &c);

            ljb[u].push_back(v);

            cost[v] = c;

            summ = summ + c;

        }

        dfs(1, 0, 0);

        printf("%d\n", summ - ff);

    }

    return 0;

}

 

你可能感兴趣的:(FZU 2195 检查站点)