传送门:http://poj.org/problem?id=2236
解题思路:
利用了并查集
在操作一:
主要判断这个维修的电脑,和已经维修好的电脑的关系,如果他们的距离不大于题中限制的距离,就把他们和并在一起。如果大于就不做处理
在操做二:
就是判断这两个电脑是否在同一个集合中,如果是在同一个集合中,那么输出“SUCCESS",否则输出”FAIL“
实现代码:
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <cstring> #include <cstdlib> using namespace std; const int maxn=10010; struct Point{ int x,y; }p[maxn]; int f[maxn]; //这是并查集 double w[maxn][maxn]; //这是用来记录第i个电脑,和其它所有电脑的关系。 bool r[maxn]; //这是记录电脑是否被维修好。 double dist(double x1,double y1,double x2,double y2){ return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } void init(int N){ for(int i=1;i<=N;i++) for(int j=1;j<=N;j++){ w[i][j]=dist(p[i].x,p[i].y,p[j].x,p[j].y); } for(int i=1;i<=N;i++){ r[i]=false; f[i]=i; } } int findfa(int a){ if(f[a]!=a) f[a]=findfa(f[a]); return f[a]; } void unit(int a,int b){ int fa=findfa(f[a]); int fb=findfa(f[b]); if(fa!=fb){ f[fa]=fb; } } int main(){ int N,D; scanf("%d%d",&N,&D); for(int i=1;i<=N;i++){ scanf("%d%d",&p[i].x,&p[i].y); } init(N); char str[3]; while(scanf("%s",str)!=EOF){ if(str[0]=='S'){ int a,b; scanf("%d%d",&a,&b); if(findfa(a)!=findfa(b)){ printf("FAIL "); } else{ printf("SUCCESS "); } }else{ int a; scanf("%d",&a); r[a]=true; for(int i=1;i<=N;i++){ if(w[a][i]<=D&&r[i]){ unit(a,i); } } } } }
代码2:
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cmath> 5 #include <vector> 6 using namespace std; 7 8 const int MAXN=1010; 9 int fa[MAXN]; 10 11 struct Node{ 12 int x,y; 13 }node[MAXN]; 14 15 double dist(Node a, Node b){ 16 double x=a.x-b.x; 17 double y=a.y-b.y; 18 return sqrt(x*x+y*y); 19 } 20 21 int findfa(int v){ 22 if(fa[v]!=v) 23 fa[v]=findfa(fa[v]); 24 return fa[v]; 25 } 26 27 void unite(int u,int v){ 28 int fu=findfa(fa[u]); 29 int fv=findfa(fa[v]); 30 if(fu!=fv) 31 fa[fu]=fv; 32 return; 33 } 34 35 void init(int n){ 36 for(int i=1;i<=n;i++) 37 fa[i]=i; 38 } 39 40 int main(){ 41 int N,d; 42 scanf("%d%d",&N,&d); 43 for(int i=1;i<=N;i++) 44 scanf("%d%d",&node[i].x,&node[i].y); 45 char str[10]; 46 vector<int> vec; 47 init(N); 48 while(scanf("%s",str)!=EOF){ 49 if(str[0]=='O'){ 50 int tmp; 51 scanf("%d",&tmp); 52 for(int i=0;i<vec.size();i++) 53 if(dist(node[tmp],node[vec[i]])<=d) 54 unite(tmp,vec[i]); 55 vec.push_back(tmp); 56 }else{ 57 int u,v; 58 scanf("%d%d",&u,&v); 59 if(findfa(u)!=findfa(v)) 60 printf("FAIL "); 61 else 62 printf("SUCCESS "); 63 } 64 } 65 66 }