zoukankan      html  css  js  c++  java
  • 洛谷 P1351 联合权值 —— 树形DP

    题目:https://www.luogu.org/problemnew/show/P1351

    树形DP,别忘了子树之间的情况(拐一下距离为2)。

    代码如下:

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    typedef long long ll;
    int const maxn=2e5+5,mod=10007;
    int n,hd[maxn],ct,to[maxn<<1],nxt[maxn<<1];
    ll w[maxn],ans,sum,mxx[maxn],s[maxn];
    int rd()
    {
      int ret=0,f=1; char ch=getchar();
      while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
      while(ch>='0'&&ch<='9')ret=(ret<<3)+(ret<<1)+ch-'0',ch=getchar();
      return ret*f;
    }
    void add(int x,int y){to[++ct]=y; nxt[ct]=hd[x]; hd[x]=ct;}
    void dfs(int x,int f)
    {
      ll ns=0,nm=0;//不是全局变量!
      for(int i=hd[x],u;i;i=nxt[i])
        {
          if((u=to[i])==f)continue;
          dfs(u,x); sum=(sum+s[u]*w[x])%mod;
          ans=max(ans,mxx[u]*w[x]);
          s[x]+=w[u]; mxx[x]=max(mxx[x],w[u]);
          sum=(sum+ns*w[u])%mod; ns+=w[u];
          ans=max(ans,nm*w[u]); nm=max(nm,w[u]);
        }
    }
    int main()
    {
      n=rd();
      for(int i=1,x,y;i<n;i++)
        {
          x=rd(); y=rd();
          add(x,y); add(y,x);
        }
      for(int i=1;i<=n;i++)w[i]=rd();
      dfs(1,0);
      printf("%lld %lld
    ",ans,(sum*2)%mod);
      return 0;
    }
  • 相关阅读:
    ios初级必看视频
    Md5加密
    Jmail发送邮件
    NPOI Helper文档
    jquery 序列化
    mvc DropDownList默认选项
    获取HTML
    EntityFramework Reverse POCO Generator工具
    全选反选
    mvc导出EXCEL
  • 原文地址:https://www.cnblogs.com/Zinn/p/9642873.html
Copyright © 2011-2022 走看看