poj 2236 Wireless Network

来源:互联网 发布:部落地震法术数据 编辑:程序博客网 时间:2024/06/10 02:42

An earthquake takes place in Southeast Asia. The ACM (Asia Cooperated Medical team) have set up a wireless network with the lap computers, but an unexpected aftershock attacked, all computers in the network were all broken. The computers are repaired one by one, and the network gradually began to work again. Because of the hardware restricts, each computer can only directly communicate with the computers that are not farther than d meters from it. But every computer can be regarded as the intermediary of the communication between two other computers, that is to say computer A and computer B can communicate if computer A and computer B can communicate directly or there is a computer C that can communicate with both A and B.

In the process of repairing the network, workers can take two kinds of operations at every moment, repairing a computer, or testing if two computers can communicate. Your job is to answer all the testing operations.

Input
The first line contains two integers N and d (1 <= N <= 1001, 0 <= d <= 20000). Here N is the number of computers, which are numbered from 1 to N, and D is the maximum distance two computers can communicate directly. In the next N lines, each contains two integers xi, yi (0 <= xi, yi <= 10000), which is the coordinate of N computers. From the (N+1)-th line to the end of input, there are operations, which are carried out one by one. Each line contains an operation in one of following two formats:
1. "O p" (1 <= p <= N), which means repairing computer p.
2. "S p q" (1 <= p, q <= N), which means testing whether computer p and q can communicate.

The input will not exceed 300000 lines.
Output
For each Testing operation, print "SUCCESS" if the two computers can communicate, or "FAIL" if not.
Sample Input
4 10 10 20 30 4O 1O 2O 4S 1 4O 3S 1 4
Sample Output
FAILSUCCESS

思路:(代码优化了一下降到一秒多跑完,有点慢哦) 并查集+点点距,详看代码;

#include<stdio.h>int pre[1010],x[10010],y[10010];int find(int t){int r=t;while(r!=pre[r])r=pre[r];int i=t,j;while(i!=r){j=pre[i];pre[i]=r;i=j;}return r;}int main(){int n,k,m,d,i,p1,p2;char s[10];scanf("%d %d",&n,&d);for(i=1;i<=n;i++){scanf("%d %d",&x[i],&y[i]);pre[i]=0;//真假值区分是否修复过i号计算机;}while(~scanf("%s",s)){if(s[0]=='O'){scanf("%d",&k);if(!pre[k])//表示k号计算机被修复;pre[k]=k;for(i=1;i<=n;i++)//把所有的计算机遍历一遍,找出与其距离小于d并且修复过的计算机,合并成一个集合;{m=(x[i]-x[k])*(x[i]-x[k])+(y[i]-y[k])*(y[i]-y[k]);//点点距;if(pre[i] && m<=d*d){int fx=find(i);int fy=find(k);if(fx!=fy)pre[fx]=fy;}}}else{scanf("%d %d",&p1,&p2);if(pre[p1] && pre[p2] && find(p1)==find(p2))//避免S 1 1 这个数据,要查看p1,p2是否被修复;printf("SUCCESS\n");else printf("FAIL\n");}}return 0;}


0 0