ZOJ 2887 Server Relocation(BFS)

来源:互联网 发布:java测试类 main方法 编辑:程序博客网 时间:2024/06/05 08:47

刚开始建图,1000 太大了,数据可能比较多,超时了.

后来就不建图了,BFS的时候算距离就可以了.

比较坑爹的是 坐标要用double存,说好的integers呢.

#include <iostream>#include <cmath>#include <cstdio>#include <vector>#include <queue>#include <memory.h>using namespace std;const int maxn = 1005;double x[maxn], y[maxn];int s, e, n;bool vis[maxn];double len1, len2;double dis(double x1, double x2, double y1, double y2){return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));}int bfs(){memset(vis, 0, sizeof(vis));queue<pair<int,int> > q;q.push(make_pair(s, 0));vis[s] = 1;while (q.size()){pair<int,int> t = q.front();q.pop();int u = t.first, tms = t.second;if(u == e)return tms;for (int i = 0; i < n; ++i){if(!vis[i] && dis(x[u], x[i], y[u], y[i]) <= len1 + len2){if(i == e)return tms + 1;vis[i] = 1;q.push(make_pair(i, tms + 1));}}}return -1;}int main(){int t;scanf("%d", &t);while (t--){int t2 = 0;scanf("%d", & t2);while (t2--){scanf("%d %d %d %lf %lf", &n, &s, &e, &len1, &len2);s--, e--;for (int i = 0; i < n; ++i){scanf("%lf %lf", &x[i], &y[i]);}int ans = bfs();if(ans == -1){printf("Impossible\n");}else{printf("%d\n", ans);}}}return 0;}


原创粉丝点击