五一模拟赛 BZOJ 1827: [Usaco2010 Mar]gather 奶牛大集会 树形DP+换根

版权声明:https://blog.csdn.net/huashuimu2003 https://blog.csdn.net/huashuimu2003/article/details/89763870

title

BZOJ 1827
LUOGU 2986
Description

Bessie正在计划一年一度的奶牛大集会,来自全国各地的奶牛将来参加这一次集会。当然,她会选择最方便的地点来举办这次集会。每个奶牛居住在 N(1<=N<=100,000) 个农场中的一个,这些农场由N-1条道路连接,并且从任意一个农场都能够到达另外一个农场。道路i连接农场A_i和B_i(1 <= A_i <=N; 1 <= B_i <= N),长度为L_i(1 <= L_i <= 1,000)。集会可以在N个农场中的任意一个举行。另外,每个牛棚中居住者C_i(0 <= C_i <= 1,000)只奶牛。在选择集会的地点的时候,Bessie希望最大化方便的程度(也就是最小化不方便程度)。比如选择第X个农场作为集会地点,它的不方便程度是其它牛棚中每只奶牛去参加集会所走的路程之和,(比如,农场i到达农场X的距离是20,那么总路程就是C_i* 20)。帮助Bessie找出最方便的地点来举行大集会。 考虑一个由五个农场组成的国家,分别由长度各异的道路连接起来。在所有农场中,3号和4号没有奶牛居住。

Input

第一行:一个整数N * 第二到N+1行:第i+1行有一个整数C_i * 第N+2行到2*N行,第i+N+1行为3个整数:A_i,B_i和L_i。

Output

  • 第一行:一个值,表示最小的不方便值。

Sample Input

5
1
1
0
0
2
1 3 1
2 3 2
3 4 3
4 5 3

Sample Output

15

Source

Gold

扫描二维码关注公众号,回复: 6124357 查看本文章

analysis

本题要用到的知识点:树形DP+容斥原理+换根

定义 f [ i ] f[i] 表示以 i i 为关键点的答案,

d i s t [ i ] dist[i] 表示以 i i 1 1 的距离,

n u m [ i ] num[i] 表示以 i i 为根的子数点权之和, s u m sum 为总点权和,

假设现在 d p dp i i 号节点, j j i i 的一个儿子, w w 为此时的边权,

那么 f [ j ] = f [ i ] + t o t n u m [ j ] w n u m [ j ] w f[j]=f[i]+(tot-num[j])*w-num[j]*w

由父节点转移到子节点,容斥会比较难想一点,建议画图理解。

code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+10;

template<typename T>inline void read(T &x)
{
    x=0;
    T f=1, ch=getchar();
    while (!isdigit(ch) && ch^'-') ch=getchar();
    if (ch=='-') f=-1, ch=getchar();
    while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
    x*=f;
}

int ver[maxn<<1],edge[maxn<<1],Next[maxn<<1],head[maxn],len;
inline void add(int x,int y,int z)
{
    ver[++len]=y,edge[len]=z,Next[len]=head[x],head[x]=len;
}
 
ll num[maxn];//num[i]记录以i为根的子树的人数和
ll dist[maxn];//dist[i]记录i到根节点的距离
ll f[maxn];//f[i]记录以i为关键点的最小路径和
ll ans,sum,c[maxn];
inline void dfs1(int x,int fa)
{
    num[x]+=c[x];
    for (int i=head[x]; i; i=Next[i])
    {
        int y=ver[i];
        if (y==fa) continue;
        dist[y]=dist[x]+edge[i];
        dfs1(y,x);
        num[x]+=num[y];
    }
}

inline void dfs2(int x,int fa)
{
    for (int i=head[x]; i; i=Next[i])
    {
        int y=ver[i];
        if (y==fa) continue;
        f[y]=f[x]+(sum-num[y]*2)*edge[i];
        ans=min(ans,f[y]);
        dfs2(y,x);
    }
}

int main()
{
	freopen("gather.in","r",stdin);
	freopen("gather.out","w",stdout);
    int n;
    read(n);
    for (int i=1; i<=n; ++i) read(c[i]),sum+=c[i];
    for (int i=1; i<n; ++i)
    {
        int x,y,z;
        read(x);read(y);read(z);
        add(x,y,z);add(y,x,z);
    }
    dfs1(1,1);
    for (int i=1; i<=n; ++i) f[1]+=1ll*c[i]*dist[i];
    ans=f[1];
    dfs2(1,1);
    printf("%lld\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/huashuimu2003/article/details/89763870