poj 2236 Wireless Network(并查集)
自己竟然写链表。。然后老错。。
#include <cstdio> #include <cstring> #include <iostream> #include <cmath> #include <algorithm> using namespace std; int n,d; typedef struct P { int x; int y; int rank; struct P *par; } P; void init(P p) { p.rank=0; p.par=NULL; } P* fnd(P *p) { P *q; q=p; cout<<"ppp"; if(q->par) { cout<<"mmm"; return p->par=fnd(q->par); } else { cout<<"nnn"; return q; } } void uion(P p1,P p2) { P *x=fnd(&p1); P *y=fnd(&p2); if(x==y)return; if(x->rank<y->rank) { x->par=y; } else { y->par=x; if(x->rank==y->rank) { x->rank++; } } } bool same(P p1,P p2) { if(!fnd(&p1)||!fnd(&p2)) { cout<<"aaa"; return false; } if(fnd(&p1)==fnd(&p2)) { cout<<"bbb"; return true; } cout<<"ccc"; return false; } bool jge(P p1,P p2) { if(sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2))<=0.0+d) return true; return false; } int main() { scanf("%d%d",&n,&d); P p[n]; P c[n]; for(int i=0; i<n; i++) scanf("%d%d",&p[i].x,&p[i].y); getchar(); char ch; int cur=0; string str; while(getline(cin,str)) { int a,b,i; if(str[0]=='O') { a=str[2]-'0'; init(p[a-1]); /* for(i=0;i<cur;i++){ if(!same(p[a-1],c[i])&&jge(p[a-1],c[i])){ uion(p[a-1],c[i]); } } if(i>=cur){ c[cur++]=p[a-1]; } */ printf("t:%d\n",a); } else if(str[0]=='S') { a=str[2]-'0'; b=str[4]-'0'; if(same(p[a-1],p[b-1]))//有错 { printf("SUCCESS\n"); } else { printf("FAIL\n"); } printf("ttt:%d,%d\n",a,b); } } }
直接用整型,i 表示数组里的第i个数 3125MS
#include <cstdio> #include <cstring> #include <iostream> #include <cmath> #include <algorithm> using namespace std; int n,d; int par[1002]; int rank[1002]; typedef struct P { int x; int y; } P; P p[1002]; void init(int x) { par[x]=x; } int fnd(int x) { if(par[x]!=x) return par[x]=fnd(par[x]); else return x; } void uion(int a,int b) { int x=fnd(a); int y=fnd(b); if(x==y)return; if(rank[x]<rank[y]) { par[x]=y; } else { par[y]=x; if(rank[x]==rank[y]) { rank[x]++; } } } bool same(int a,int b) { if(fnd(a)==fnd(b)) { return true; } return false; } bool jge(int a,int b) { P p1=p[a]; P p2=p[b]; if(sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2))<=0.0+d) return true; return false; } int main() { scanf("%d%d",&n,&d); int c[n]; for(int i=1; i<=n; i++) scanf("%d%d",&p[i].x,&p[i].y); getchar(); int cur=0; char ch; while(scanf("%c",&ch)==1) //getline()虽然也能Z+ENTER但是提交会运行时错误 { int a,b,i; if(ch=='O') { scanf("%d",&a); init(a); for(i=0; i<cur; i++) { if(!same(a,c[i])&&jge(a,c[i])) { uion(a,c[i]); } } if(i>=cur) { c[cur++]=a; } } else if(ch=='S') { scanf("%d%d",&a,&b); if(same(a,b)) { printf("SUCCESS\n"); } else { printf("FAIL\n"); } } getchar(); } }

浙公网安备 33010602011771号