码迷,mamicode.com
首页 > 其他好文 > 详细

换根DP

时间:2019-10-30 16:33:19      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:iostream   max   names   class   二次   clu   扫描   const   string   

换根dp的通法:1.第一次扫描时,任选一个点为根,在“有根树”上执行一次树形DP,也就在回溯时发生的,自底向上的状态转移。

2.第二次扫描时,从刚才选出的根出发,对整棵树执行一次dfs,在每次递归前进行自上向下的推导,计算出换根后的解。

1.POJ3585 Accumulation Degree

dp[i]以i为根的子树中,把i作为源点的最大流量

转移\(dp[x]=\sum_{y\epsilon son(x)}^{}\left\{\begin{matrix} min(dp[y],len[p]) & du[y]>1\\ len[p]& du[y]=1 \end{matrix}\right.\)

f[i]表示以i为源点的最大流量。

转移:\(f[y]=dp[y]+\left\{\begin{matrix} min(f[x]-min(dp[y],len[p]),len[p]) & du[x]>1\\ len[p]& du[x]=1 \end{matrix}\right.\)

#include<queue>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
using namespace std;
typedef long long ll;
const int maxm=2e5+7;
int t,n;
int last[maxm],other[maxm+maxm],len[maxm<<1],pre[maxm<<1],l;
int dp[maxm];//以i为根的子树中,把i作为源点的最大流量
int f[maxm];//以i为源点的最大流量 
int du[maxm];
void add(int x,int y,int z)
{
 l++;
 pre[l]=last[x];
 last[x]=l;
 other[l]=y;
 len[l]=z;  
}
void dfs(int x,int fa)
{
  for(int p=last[x];p;p=pre[p])
  {
    int v=other[p];
    if(v==fa) continue;
    dfs(v,x);
    if(du[v]!=1)dp[x]+=min(dp[v],len[p]);
    if(du[v]==1) dp[x]+=len[p]; 
  }
}
void dfs1(int x,int fa)
{
 for(int p=last[x];p;p=pre[p])
 {
  int v=other[p];
  if(v==fa) continue;
  if(du[x]==1)
  f[v]=dp[v]+len[p];
  else f[v]=dp[v]+min(f[x]-min(dp[v],len[p]),len[p]);//f[x]-min(dp[v],len[p])为x流向其他部分的流量 
  dfs1(v,x);
 }
}
int main()
{
 scanf("%d",&t);
 while(t--)
 {
  memset(last,0,sizeof(last));
  l=0;
  memset(du,0,sizeof(du));
  memset(dp,0,sizeof(dp));
  scanf("%d",&n);
  for(int i=1;i<=n-1;i++)
  {
   int x,y,z;
   scanf("%d%d%d",&x,&y,&z);
   add(x,y,z);
   add(y,x,z);
   du[x]++;
   du[y]++;
  }
  dfs(1,0);//先以1为根
  f[1]=dp[1];
  dfs1(1,0);
  int ans=0;
  for(int i=1;i<=n;i++)
  ans=max(ans,f[i]);
  printf("%d\n",ans); 
 }
 return 0;  
}

换根DP

标签:iostream   max   names   class   二次   clu   扫描   const   string   

原文地址:https://www.cnblogs.com/lihan123/p/11765406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!