问一道算法题:取一点集的子集,使得子集内任意点间距离小于K

sunlitpalm 2012-07-18 03:49:50
You are given a tree that has N vertices and N-1 edges. Your task is to mark as small number of verices as possible so that the maximum distance between two unmarked vertices be less than or equal to K. You should write this value to the output.
Distance between two vertices i and j is defined as the minimum number of edges you have to pass in order to reach vertex i from vertex j.

Input:
The first line of input contains two integers N and K. next N-1 lines contains two integers 1 <= ui,vi <= N. Each of these lines specifies an edge.
N is no more than 100. K is less than N.

Output:
On the only line of the output print an integer being the result of the test.

Sample Input:

5 1
1 2
1 3
1 4
1 5

Sample Output:

3

Sample Input:

5 2
1 2
1 3
1 4
1 5

Sample Output:

0

Explanation:

In the first case you have to mark at least 3 vertices, and in the second example you don't need to mark any vertices.

我的想法是先计算任意两点间的最短距离。然后统计距某点距离大于K的点数,记为该点权重,

取最大权重点,删除之,并将与之相连且距离大于K的点权重减一;直到取到最大权重点的权重为0。

我的解法可以得到题目中数据的结果,自己写了几组数据也是对的,但是提交后的其他的运行数据都失败了。请问我的解法有什么问题?
谢谢
...全文
300 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
谢潇雨 2012-09-09
  • 打赏
  • 举报
回复
说错了一点删除5后,1的权重依然为4
谢潇雨 2012-09-09
  • 打赏
  • 举报
回复
“取最大权重点,删除之,并将与之相连且距离大于K的点权重减一”我觉得这里逻辑不严谨,举个反例,6 2;1 2;2 3;3 4;4 5;4 6。这时候最大权重点在两端,且有三个点,而这时候三个都是最大权重点,删除的方式不同,结果也不同,若删除1和2则结果是对的,若删除 5 、6和1结果就大了。况且,你删除5后,6的权重依然为4,不需要减一。
  • 打赏
  • 举报
回复
贴下题目地址吧

33,027

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧