201403-4 無線網路
阿新 • • 發佈:2020-08-20
思路
測試資料很弱,用廣搜就可以找到最短路。但是貪心演算法應該不能每次都找到最優解。
如果可以在超過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); }