Luogu2986 [USACO10MAR]伟大的奶牛聚集 (树形DP)
阅读原文时间:2023年07月08日阅读:1

有点权的重心,拆掉点dfs不就是了吗

//#include <iostream>
#include <cstdio>
#include <cstring>
//#include <algorithm>
//#include <cmath>
#define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long

#define ON_DEBUG

#ifdef ON_DEBUG

#define D_e_Line printf("\n\n----------\n\n")
#define D_e(x)  cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin);

#else

#define D_e_Line ;
#define D_e(x)  ;
#define Pause() ;
#define FileOpen() ;

#endif

struct ios{
    template<typename ATP>ios& operator >> (ATP &x){
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x*= f;
        return *this;
    }
}io;
using namespace std;

const int N = 100007;

struct Edge{
    int nxt, pre, w;
}e[N << 1];
int head[N], cntEdge;
inline void add(int u, int v, int w){
    e[++cntEdge] = (Edge){ head[u], v, w}, head[u] = cntEdge;
}

int C[N], totSize;
int siz[N];
long long f[N];
inline void DFS_1(int u, int fa){
    siz[u] = C[u];
    for(register int i = head[u]; i; i = e[i].nxt){
        int v = e[i].pre;
        if(v == fa) continue;
        DFS_1(v, u);
        siz[u] += siz[v];
        f[u] += f[v] + 1ll * siz[v] * e[i].w;
    }
}
long long ans = 9223372036854775807;
inline void DFS_2(int u, int fa){
    for(register int i = head[u]; i; i = e[i].nxt){
        int v = e[i].pre;
        if(v == fa) continue;
        f[v] = f[u] - 1ll * siz[v] * e[i].w + 1ll * (totSize - siz[v]) * e[i].w;
        ans = Min(ans, f[v]);
        DFS_2(v, u);
    }
}
int main(){
//FileOpen();
    int n;
    io >> n;
    R(i,1,n){
        io >> C[i];
        totSize += C[i];
    }
    R(i,2,n){
        int u, v, w;
        io >> u >> v >> w;
        add(u, v, w);
        add(v, u, w);
    }

//    DFS_First(1, 0);
//    DFS_Second(1, 1);
//
//    long long ans = 9223372036854775807;
//    R(i,1,n){
//        long long sum = 0;
//        R(j,1,n){
//            if(i == j) continue;
//            sum += 1ll * (dis[i] - (dis[LCA(i, j)] << 1) + dis[j]) * C[j];
//        }
//        ans = Min(ans, sum);
//    }

    DFS_1(1, 0);
    for(register int i = 2; i <= n; i += 3) f[i] = f[i + 1] = f[i + 2] = 0;
    DFS_2(1, 0);

    printf("%lld", ans);

    return 0;
}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章