题目来源
http://bailian.openjudge.cn/practice/2394/
解题思路
- 这道题目就是计算从源点1到其他顶点之间的最短距离,使用Dijkstra算法即可实现,然后判断每头牛所在的点,判断其和源点1之间的距离是否不超过M。
- 代码运行了很多遍之后发现老是出错,最后发现测试数据集中会出现重复的边,比如2 3 1,表示2号顶点到3号顶点距离为1,但是还会出现2 3 100,表示2号顶点到3号顶点最短距离是100,我的输入中构造图的时候就会更新为2号到3号的距离为100,但是实际计算按照1来计算,因此,读取P条边的时候,采用如下代码读取每条边的距离,结果一直无法通过。
1 | scanf("%d%d%d",&x, &y, &w); |
最后知道了错误后改用如下读取方式,最终AC了。
1 | scanf("%d%d%d",&x, &y, &w); |
- 这算是一个经验教训吧,以后读取图的边的时候,不要随时更新,读取两个顶点的距离时,保存最小值就好。
算法实现
1 |
|
测试数据集
- test case 1—input
1 | 7 6 5 8 |
- test case 1—output
1 | 4 |
- test case 2—input
1 | 1 1 1 1 |
- test case 2—output
1 | 1 |
- test case 3—input
1 | 11 10 10 20 |
- test case 3—output
1 | 10 |
- test case 4—input
1 | 3 2 10 4 |
- test case 4—output
1 | 7 |
- test case 5—input
1 | 11 22 12 69999 |
- test case 5—output
1 | 11 |
- test case 6—input
1 | 5 5 10 100 |
- test case 6—output
1 | 8 |
- test case 7—input
1 | 10 10 11 70000 |
- test case 7—output
1 | 10 |
- test case 8—input
1 | 50 100 50 1000 |
- test case 8—output
1 | 24 |
- test case 9—input
1 | 500 100 100 70000 |
- test case 9—output
1 | 2 |
- test case 10—input
1 | 50 1000 100 69999 |
- test case 10—output
1 | 52 |
- test case 11—input
1 | 500 499 100 70000 |
- test case 11—output
1 | 99 |
- test case 12—input
1 | 500 499 100 70000 |
- test case 12—output
1 | 1 |