bzoj1827(树形dp)

来源:互联网 发布:如何开农村淘宝网店 编辑:程序博客网 时间:2024/05/22 01:53

以前见过这样思路的题,所以就不难。。。。

不过,我终于遇见到了最大值不够大,然后wa的情况了。。。。

最后把最大值开到12345678910111213才过。。。17位啊


#include<cstdio>#include<cstring>#include<cstdlib>#include<cmath>#include<algorithm>using namespace std;typedef long long ll;const int N=120005;int c[N],n;int fa[N],head[N],tot;struct aa{int to,pre,dis;}edge[N*5];void addedge(int x,int y,int z){edge[++tot].to=y;edge[tot].dis=z;edge[tot].pre=head[x];head[x]=tot;}ll f[N],size[N],ans=12345678910111213ll;void dfs1(int u){size[u]=c[u];for (int i=head[u];i;i=edge[i].pre)if (edge[i].to!=fa[u]){int v=edge[i].to;fa[v]=u;dfs1(v);size[u]+=size[v];f[u]+=f[v]+(ll)size[v]*edge[i].dis;}}void dfs2(int u,ll upsize,ll upf){ans=min(ans,upf+f[u]);for (int i=head[u];i;i=edge[i].pre)if (edge[i].to!=fa[u]){int v=edge[i].to;ll sz=upsize+size[u]-size[v];ll downf=upf+f[u]-f[v]+sz*edge[i].dis-(ll)size[v]*edge[i].dis;dfs2(v,sz,downf);}}int main(){scanf("%d",&n);for (int i=1;i<=n;i++) scanf("%d",&c[i]);int x,y,z;for (int i=1;i<n;i++){scanf("%d%d%d",&x,&y,&z);addedge(x,y,z);addedge(y,x,z);}dfs1(1);dfs2(1,0,0);printf("%lld",ans);return 0;}


0 0