其他分享
首页 > 其他分享> > 伟大的牛的聚会

伟大的牛的聚会

作者:互联网

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 100005
#define ll long long
using namespace std;
inline int read()
{
    int x = 0, f = 1;
    char c = getchar();
    while (c < '0' || c > '9')
    {
        if (c == '-')
            f = -1;
        c = getchar();
    }
    while (c >= '0' && c <= '9')
    {
        x = x * 10 + c - '0';
        c = getchar();
    }
    return x * f;
}
ll ans = 1e15, f[N], c[N], q[N];
// f在两次dfs里含义不一样 c是每个点有多少牛 q是每个点和他的子树总共有多少牛
int tot, head[N], n;

struct edge
{
    int to, nxt, w;
    edge() {}
    edge(int x, int y, int z) { to = x, nxt = y, w = z; }
} a[2 * N];
//邻接表存图
void add(int from, int to, int w)
{
    a[++tot] = edge(to, head[from], w);
    head[from] = tot;
}

void dfs(int x, int fa)
{
    q[x] += c[x];
    for (int i = head[x]; i; i = a[i].nxt)
    {
        int u = a[i].to, s = a[i].w;
        if (u != fa)
        {
            dfs(u, x);
            q[x] += q[u];
            f[x] += f[u] + q[u] * s;
        }
    }
}
//第一次dfs 求出A1
void dfs2(int x, int fa)
{
    for (int i = head[x]; i; i = a[i].nxt)
    {
        int u = a[i].to, s = a[i].w;
        if (u != fa)
        {
            // cout << "u = " << u << endl;
            f[u] = f[x] + (q[1] - q[u]) * s - q[u] * s;
            // printf("f[%d] = %lld\n", u, f[u]);
            dfs2(u, x);
        }
    }
}
//第二次dfs 求出每个点的答案
int main()
{
    n = read();
    for (int i = 1; i <= n; i++)
        c[i] = read();
    for (int i = 1; i < n; i++)
    {
        int a1 = read(), a2 = read(), a3 = read();
        add(a1, a2, a3);
        add(a2, a1, a3);
    }
    dfs(1, 1);
    // for (int i = 1; i <= n; i++)
    // {
    //     cout << f[i] << endl;
    // }
    dfs2(1, 1);
    for (int i = 1; i <= n; i++)
        ans = min(ans, f[i]); //在所有点中找到最方便的
    cout << ans << endl;
    return 0;
}

标签:int,long,define,while,聚会,伟大,include,getchar
来源: https://www.cnblogs.com/Atoli-Sego/p/16531813.html