uvalive4614 (这题不懂)

题意:给你一棵树,有一些点你需要去一定的次数,每去一次你都要回来,求最小的权值和

参考的代码:

#include <iostream> 
#include <cstdio> 
#include <cstring> 
#include <algorithm> 
#define INF 1000000000000000LL 
using namespace std;  
const int MAXN = 50010;  

int n,m,num,cas,u,v;  
long long ans,sum,w;  
int head[MAXN],next[MAXN*2],ev[MAXN*2],temp[MAXN];  
long long fre[MAXN],f[MAXN],ew[MAXN*2],dp[MAXN],dis[MAXN];  

void addedge(int u,int v,long long w){  
    next[++num] = head[u];  
    head[u] = num;  
    ev[num] = v;  
    ew[num] = w;  
}  

void read(){  
    memset(head,-1,sizeof(head));  
    memset(fre,0,sizeof(fre));  
    num = -1;  
    scanf("%d",&n);  
    for (int i = 0; i < n-1; i++){  
        scanf("%d%d%lld",&u,&v,&w);  
        addedge(u,v,w);  
        addedge(v,u,w);  
    }  
    sum = 0;  
    scanf("%d",&m);  
    for (int i = 0; i < m; i++){  
        scanf("%d%lld",&u,&w);  
        fre[u] = w;  
        sum += fre[u];  
    }  
}  

void pre_dfs(int fa,int u){  
    f[u] = 0;  
    dis[u] = 0;  
    for (int i = head[u]; i != -1; i = next[i])  
        if (ev[i] != fa){  
            pre_dfs(u,ev[i]);  
            dis[u] += dis[ev[i]] + 2 * ew[i] * f[ev[i]];  
            f[u] += f[ev[i]];  
        }  
    f[u] += fre[u];  
}  

void dfs(int fa,int u,long long dis){  
    dp[u] = dis;  
    if (dp[u] < ans)  
        ans = dp[u];  
    for (int i = head[u]; i != -1; i = next[i])  
        if (fa != ev[i])  
            dfs(u,ev[i],dis+2*ew[i]*(sum-2*f[ev[i]]));  //为什么是这样?
}  

void solve(){  
    pre_dfs(1,1);  
    ans = INF;  
    dfs(1,1,dis[1]);  
    printf("%lld\n",ans);  
    int cnt = -1;  
    for (int i = 1; i <= n; i++)  
        if (dp[i] == ans)  
            temp[++cnt] = i;  
    for (int i = 0; i <= cnt; i++)  
        if (i != cnt)  
            printf("%d ",temp[i]);  
        else printf("%d\n",temp[i]);  
}  

int main(){  
    scanf("%d",&cas);  
    while (cas--){  
        read();  
        solve();  
    }  
    return 0;  
}  

你可能感兴趣的:(uvalive4614 (这题不懂))