POJ 2236 Wireless Network (並查集)
阿新 • • 發佈:2017-08-17
left amp sscanf namespace ets ring ace tco scan
題意:
有n臺損壞的電腦,現要將其逐臺修復,且使其相互恢復通信功能。若兩臺電腦能相互通信,則有兩種情況,一是他們之間的距離小於d,二是他們可以借助都可到達的第三臺已修復的電腦。給出所有電腦的坐標位置,對其進行兩種可能的操作,O x表示修復第x臺,S x y表示判斷x y之間能否通信,若能輸出SUCCESS,否則輸出FALL。
思路:
用並查集來保存電腦互相的連通情況。
每次修好電腦後,將它可以通信的電腦(距離滿足且已修好)與它進行連通。
#include <cstdio> #include <cstring> #include <string> #include <iostream> using namespace std; const int maxn = 1000 + 5; struct node{ int x, y; }pos[maxn]; int p[maxn], vis[maxn]; int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); } void unionset(int x, int y) { int px = find(x), py = find(y); if (px != py) p[px] = py; } int main() { int n, d; scanf("%d%d", &n, &d); memset(vis, 0, sizeof(vis)); for (int i = 1; i <= n; ++i) p[i] = i; for (int i = 1; i <= n; ++i) scanf("%d%d", &pos[i].x, &pos[i].y); getchar(); char s[20]; while (fgets(s, sizeof(s), stdin) != NULL) { char op; int a, b; if (s[0] == ‘S‘) { sscanf(s, "%c %d %d", &op, &a, &b); int rx = find(a), ry = find(b); if (rx == ry) printf("SUCCESS\n"); else printf("FAIL\n"); } else { sscanf(s, "%c %d", &op, &a); vis[a] = 1; int x = pos[a].x, y = pos[a].y; for (int i = 1; i <= n; ++i) { if (a == i || !vis[i]) continue; int x1 = pos[i].x, y1 = pos[i].y; if ((x - x1)*(x - x1) + (y - y1)*(y - y1) <= d*d) { unionset(a, i); } } } } return 0; }
POJ 2236 Wireless Network (並查集)