FZU - 2038 Another Postman Problem

题意:对于每一条边,它的访问次数等于它子树的节点个数*剩余的节点个数

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXN = 100010;

struct node{
    int v,w;
    node(){}
    node(int a,int b){
        v = a;
        w = b;
    }
};
int vis[MAXN],T,n;
vector<node> G[MAXN];
long long ans;

long long cal(int u){
    vis[u] = 1;
    int size = G[u].size();
    long long sum = 1,temp;
    for (int i = 0; i < size; i++){
        int v = G[u][i].v;
        if (vis[v])
            continue;
        temp = cal(v);
        ans += 2 * G[u][i].w * temp * (n-temp);
        sum += temp;
    }
    return sum;
}

int main(){
    int t,u,v,w,cas=1;
    scanf("%d",&t);
    while (t--){
        for (int i = 0; i < MAXN; i++)
            G[i].clear();
        memset(vis,0,sizeof(vis));
        scanf("%d",&n);
        for (int i = 1; i < n; i++){
            scanf("%d%d%d",&u,&v,&w);
            G[u].push_back(node(v,w));
            G[v].push_back(node(u,w));
        }
        ans = 0;
        cal(0);
        printf("Case %d: %lld\n",cas++,ans);
    }
    return 0;
}



你可能感兴趣的:(FZU - 2038 Another Postman Problem)