我是 A 题

我是 A 题

https://ac.nowcoder.com/acm/contest/8563/B

dfs+链式前向星存图

题目分析:我们以每个叶子节点去寻找能够构成连通块的结点,如果当前节点已经是k的倍数了,那么就不用去寻找其他节点,也就是说连接父节点的那条边可以去掉,然后一直自下而上的去寻找,如果当前子树的权值和是k的倍数,那么说明这个子树可以自成一体不用去寻找其他节点来合并了

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e6 + 10;
ll a[maxn], head[maxn], tot, ans, n, k;
struct node
{
    int to, w, next;
} edge[maxn];
void add(ll u, ll v, ll w)
{
    edge[++tot].to = v;
    edge[tot].w = w;
    edge[tot].next = head[u];
    head[u] = tot;
}

void dfs(ll s, ll e)
{
    for (int i = head[s]; ~i; i = edge[i].next)
    {
        if (edge[i].to == e)
            continue;
        dfs(edge[i].to, s);
        if (a[edge[i].to])
        {
            ans += edge[i].w;
            a[s] += a[edge[i].to];
        }
    }
    a[s] %= k;
}
int main()
{
    memset(head, -1, sizeof(head));
    scanf("%lld%lld", &n, &k);
    for (int i = 1; i <= n; ++i)
    {
        scanf("%lld", &a[i]);
        a[i] %= k;
    }
    for (int i = 1; i < n; ++i)
    {
        ll u, v, w;
        scanf("%lld%lld%lld", &u, &v, &w);
        add(u, v, w);
        add(v, u, w);
    }
    dfs(1, 0);
    printf("%lld\n", ans);
    return 0;
}
牛客比赛系列题解 文章被收录于专栏

加油加油

全部评论

相关推荐

接好运Plus:定时器项目都被用烂了,感觉
点赞 评论 收藏
分享
10-09 17:17
已编辑
门头沟学院 Java
活泼的代码渣渣在泡池...:同学你好,我也是学院本,后天要面这个亚信科技,是实习,请问问题都啥样呀,我项目就做了网上的,这是第一次面试
投递多益网络等公司10个岗位
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务