ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

伟大的牛的聚会

2022-07-29 12:00:45  阅读:100  来源: 互联网

标签:int long define while 聚会 伟大 include getchar


#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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有