【bzoj4033】HAOI2015树上染色

树形dp。

#include<bits/stdc++.h>
#define N 2010
using namespace std;
typedef long long ll;
int n,k,tot=0,head[N];
struct Node{int u,v,w,next;}G[N<<1];
inline void addedge(int u,int v,int w){
    G[tot].u=u;G[tot].v=v;G[tot].w=w;G[tot].next=head[u];head[u]=tot++;
    G[tot].u=v;G[tot].v=u;G[tot].w=w;G[tot].next=head[v];head[v]=tot++;
}
ll dp[N][N];int size[N];
void dfs(int u,int fa){
    size[u]=1;memset(dp[u],-1,sizeof(dp[u]));dp[u][0]=dp[u][1]=0;
    for(int i=head[u];~i;i=G[i].next){
        int v=G[i].v;if(v==fa)continue;
        dfs(v,u);size[u]+=size[v];
    }
    for(int i=head[u];~i;i=G[i].next){
        int v=G[i].v;if(v==fa)continue;int w=G[i].w;
        for(int i=min(k,size[u]);i>=0;i--)
        for(int j=0;j<=min(i,size[v]);j++)if(~dp[u][i-j]){
            ll val=(ll)j*w*(k-j)+(ll)(size[v]-j)*(n-k+j-size[v])*w;
            dp[u][i]=max(dp[u][i],dp[u][i-j]+dp[v][j]+val);
        }
    }
}
inline int read(){
    int f=1,x=0;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(ch<'0'||ch>'9');
    do{x=x*10+ch-'0';ch=getchar();}while(ch>='0'&&ch<='9');
    return f*x;
}
int main(){
    memset(head,-1,sizeof(head));
    n=read();k=read();
    for(int i=1;i<n;i++){
        int u=read(),v=read(),w=read();
        addedge(u,v,w);
    }
    dfs(1,0);
    printf("%lld\n",dp[1][k]);
}

 

posted @ 2017-06-12 19:42  zcysky  阅读(236)  评论(0编辑  收藏  举报