zoukankan      html  css  js  c++  java
  • POJ 2236 Wireless Network (并查集)

    题意:

    有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
    ");
    			else printf("FAIL
    ");
    		}
    		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;
    }
  • 相关阅读:
    最小化x11 debian
    chroot后 运行xeyes Error: Can't open display: :0.0
    std::bind1st和std::bind2nd
    bind1nd,not1,compose1等用法
    python中*和**的参数
    QT静态编译
    Qt中QEvent和信号槽的区别
    JSON文件内容加注释的几种方法
    C语言--#、##、__VA_ARGS__ 和##__VA_ARGS__ 的使用
    QT正则表达式
  • 原文地址:https://www.cnblogs.com/demian/p/7376347.html
Copyright © 2011-2022 走看看