题意:给你一棵树,有一些点你需要去一定的次数,每去一次你都要回来,求最小的权值和
思路:首先将无根树转化话有根树,然后初始化一次求到根的权值和以及每个子树需要去的次数,然后就是怎么求最小的权值和,已知dp[u],怎么求它的子节点v的dp[v],
dp[v] = dp[u] + (sum-f[v])*len - len*f[v],sum表示总的次数,len表示(u,v)的权值的两倍,根据父子节点的关系可以推出来
#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; }