前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Archived | 310-01-ACOJ-0488-统计节点

Archived | 310-01-ACOJ-0488-统计节点

作者头像
gyro永不抽风
发布2021-05-21 11:38:42
3740
发布2021-05-21 11:38:42
举报

310-01-ACOJ-0488-统计节点

题目大意:

给定一棵有n 个结点的树,给定树上m 个点,称作标兵,再给定一个距离范围k 。求树上有多少点,其本身不是标兵,且到每个标兵的距离都不超过k 。每条边的长度固定为1

题解:

对于这道题,要统计距离所有标兵的距离都不超过k 的个数。换言之,就是统计节点,对于每一个满足要求的节点,要有其距离最远的标兵的距离不超过k

有了这个想法,不妨构造出叶子节点均为标兵的且包含所有标兵的最小生成树。现在求这棵子树上的直径,或者说是这颗子树上的距离最远的两个端点。

所以题目就转换为统计所有节点,节点满足距离这两个端点都不超过k 。(证明略,反证法,而且任意一条子树的直径都是可行的)。

代码:

代码语言:javascript
复制
#include <iostream>

using namespace std;

const int maxn = 100005;
int n, m, k;
int t_point[maxn], head[maxn], dist_1[maxn], dist_2[maxn], dist_3[maxn];
bool isImPoint[maxn];

struct edge {
    int to, next;
} g[maxn << 1];

int ecnt = 2;

void add_edge(int u, int v) {
    g[ecnt] = (edge) {v, head[u]};
    head[u] = ecnt ++;
}

void dfs(int u, int fa, int P) {
    for (int e = head[u]; e != 0; e = g[e].next) {
        int v = g[e].to;
        if (v == fa) continue;
        if (P == 1) dist_1[v] = dist_1[u] + 1;
        if (P == 2) dist_2[v] = dist_2[u] + 1;
        if (P == 3) dist_3[v] = dist_3[u] + 1;
        dfs(v, u, P);
    }
}

int main() {
        cin >> n >> m >> k;
    for (int i = 1; i <= m; i ++) {
        cin >> t_point[i];
        isImPoint[t_point[i]] = true;
    }
    for (int i = 1; i < n; i ++) {
        int u, v; cin >> u >> v;
        add_edge(u, v); add_edge(v, u);
    }
        dfs(1, 0, 1);
        int node_first = 0;
        for (int i = 1; i <= m; i ++)
                if (dist_1[t_point[i]] >= dist_1[node_first]) node_first = t_point[i];
        dfs(node_first, 0, 2);
        int node_second = 0;
        for (int i = 1; i <= m; i ++)
                if (dist_2[t_point[i]] >= dist_2[node_second]) node_second = t_point[i];
        dfs(node_second, 0, 3);
        int cnt = 0;
        for (int i = 1; i <= n; i ++) {
                if (isImPoint[i]) continue;
                if (dist_2[i] <= k && dist_3[i] <= k)
                        cnt ++;
        }
        cout << cnt << endl;
        return 0;
}

本文作者:博主: gyrojeff    文章标题:Archived | 310-01-ACOJ-0488-统计节点

本文地址:https://cloud.tencent.com/developer/article/1827239

版权说明:若无注明,本文皆为“gyro永不抽风!”原创,转载请保留文章出处。

许可协议:署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 转载请保留原文链接及作者!

我的博客即将同步至腾讯云+社区,邀请大家一同入驻

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020 年 03 月,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 310-01-ACOJ-0488-统计节点
    • 题目大意:
      • 题解:
        • 代码:
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档