Codeforces 161D Distance in Tree

本文介绍了一种使用树形动态规划方法解决特定图论问题的算法。该算法用于计算一棵树中具有确切距离k的不同顶点对的数量。通过深度优先搜索进行两轮遍历,第一轮遍历计算每个节点到其子节点的距离分布,第二轮遍历计算满足条件的顶点对数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A tree is a connected graph that doesn’t contain any cycles.

The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.

You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.

Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.

Next n - 1 lines describe the edges as “ai bi” (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.

Output
Print a single integer — the number of distinct pairs of the tree’s vertices which have a distance of exactly k between them.

Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Sample test(s)
input
5 2
1 2
2 3
3 4
2 5
output
4
input
5 3
1 2
2 3
3 4
4 5
output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4).

解题思路:简单树形DP。

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <utility>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long ll;
const int maxn = 50010;
ll dp1[maxn][510];
ll dp2[maxn];
int n, k;
ll  ans;

struct Edge {
    int v, next;
    Edge() { }
    Edge(int _v, int _next) : v(_v), next(_next) { }
}edges[2*maxn];
int head[maxn], edge_sum;

void init_graph() {
    edge_sum = 0;
    memset(head, -1, sizeof(head));
}

void add_edge(int u, int v) {
    edges[edge_sum].v = v;
    edges[edge_sum].next = head[u];
    head[u] = edge_sum++;

    edges[edge_sum].v = u;
    edges[edge_sum].next = head[v];
    head[v] = edge_sum++;
}

void dfs1(int u, int fa) {
    dp1[u][0] += 1;
    for(int i = head[u]; i != -1; i = edges[i].next) {
        int v = edges[i].v;
        if(v == fa) continue;
        dfs1(v, u);
        for(int j = 0; j < k; ++j) {
            dp1[u][j+1] += dp1[v][j];
        }
    }
    return ;
}

int par[maxn][510];

void dfs2(int u, int fa) {
    par[u][0] = u;
    dp2[u] = dp1[u][k];
    if(fa != -1) {
        for(int i = 1; i <= k; ++i) {
            par[u][i] = par[fa][i-1];
        }
        for(int i = 1; i <= k; ++i) {
            if(par[u][i] == -1) break;
            dp2[u] += dp1[par[u][i]][k-i];
            if(k-i-1 >= 0) {
                dp2[u] -= dp1[par[u][i-1]][k-i-1];
            }
        }
    }
    ans += dp2[u];
    for(int i = head[u]; i != -1; i = edges[i].next) {
        int v = edges[i].v;
        if(v == fa) continue;
        dfs2(v, u);
    }
    return ;
}


int main() {


    //freopen("aa.in", "r", stdin);

    int u, v;
    scanf("%d %d", &n, &k);
    init_graph();
    for(int i = 1; i < n; ++i) {
        scanf("%d %d", &u, &v);
        add_edge(u, v);
    }
    ans = 0;
    dfs1(1, -1);
    memset(par, -1, sizeof(par));
    dfs2(1, -1);
    printf("%I64d\n", ans/2);
    return 0;
}
### 解决方案概述 对于给定的问题,在一维坐标系中有 N 个点,每个点具有特定的权重 w。如果两个点之间的距离大于它们各自权重之和,则这两个点之间可以建立一条边。目标是从这些点中找到最大数量的点使得任意两点间均存在边。 为了实现这一目的,可以通过构建不等式 Xi-Wi ≥ Xj+Wj 来确定有向图中的节点关系[^3]。具体来说: - 对于每一对不同的点 (Xi, Wi) 和 (Xj, Wj),当 Xi > Xj 并且 Xi - Wi >= Xj + Wj 成立时,表示从 j 到 i 存在一个方向。 - Xj| >= Wi + Wj 的判断过程。 基于上述分析,算法设计如下: 1. 创建一个新的数组 P[],其中存储的是经过变换后的数据对 (Xi + Wi, Xi - Wi)。 2. 将此新创建的数据集按照第二个分量升序排列;如果有相同的情况,则按第一个分量降序处理。 3. 初始化计数器 count=0 及当前最小右端点 cur_min_right=-&infin;。 4. 遍历排序后的列表: - 如果当前元素的第一个分量大于等于cur_min_right,则更新count并设置新的cur_min_right为该元素的第二分量。 5. 输出最终的结果即为所求的最大团大小。 以下是 Python 实现代码示例: ```python def max_clique(n, points): # 计算转换后的点集合 [(xi+wi, xi-wi)] transformed_points = sorted([(points[i][0]+points[i][1], points[i][0]-points[i][1]) for i in range(n)], key=lambda x:(x[1], -x[0])) result = 0 current_end = float('-inf') for start, end in transformed_points: if start >= current_end: result += 1 current_end = end return result ``` 通过这种方法能够有效地解决问题,并获得最优解。值得注意的是,这里采用了一种贪心策略来逐步增加符合条件的顶点数目,从而保证了结果是最优的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值