思路
测试数据很弱,用广搜就可以找到最短路。但是贪心算法应该不能每次都找到最优解。
如果可以在超过K个位置中选择添加路由器实现更短的路径,那么贪心的选择就是最先搜索到的k个位置。换句话说贪心认为无论在哪里添加路由器,减少中转的效果是一样的。列举一些简单情况可以证明这是不合理的。
实现
#include <iostream>
#include <cmath>
#include <queue>
#define MAX_ROUTERS 0xff
#define pow(x) ((x)*(x))
struct point {
long long x;
long long y;
};
struct node {
int id;
int level;
int append_num;
node (int id, int level,int append_num): id(id), level(level), append_num(append_num) {}
};
int routers_number, unused_point_number, append_number;
long long dist;
point routers[MAX_ROUTERS];
bool graph[MAX_ROUTERS][MAX_ROUTERS];
bool visit[MAX_ROUTERS];
int dfs(int start, int target) {
int count = 0;
node origin = node(start, 0, 0);
std::queue<node> nodes;
nodes.push(origin);
while (!nodes.empty()) {
node point_tmp = nodes.front();
nodes.pop();
int temp_level = point_tmp.level;
int temp_append_num = point_tmp.append_num;
if (point_tmp.id == target) {
return point_tmp.level - 1;
}
int i;
for (i = 0;i < routers_number;++i) {
if (!visit[i] && graph[point_tmp.id][i]) {
nodes.push(node(i, temp_level + 1,temp_append_num));
visit[i] = true;
}
}
for (;i < routers_number + unused_point_number;++i) {
if (!visit[i] && graph[point_tmp.id][i]
&& temp_append_num < append_number) {
nodes.push(node(i, temp_level + 1,temp_append_num + 1));
visit[i] = true;
}
}
}
}
int main() {
std::cin >> routers_number
>> unused_point_number
>> append_number;
std::cin >> dist;
int i,j;
for (i = 0;i < routers_number + unused_point_number;++i) {
std::cin >> routers[i].x >> routers[i].y;
}
for (i = 0;i < routers_number + unused_point_number;++i) {
for (j = i+1;j < routers_number + unused_point_number;++j) {
graph[i][j] = graph[j][i]
= std::sqrt(pow(routers[i].x-routers[j].x)+
pow(routers[i].y-routers[j].y)) <= dist;
}
}
std::cout << dfs(0,1);
}