标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 21693 Accepted Submission(s): 6856
#include<cstdio> #include<cmath> #include<vector> #include<queue> using namespace std; const int MAXN=105; const double INF=1.0e9; typedef pair<double,int> P; struct Point{ int x,y; }ps[MAXN]; int V; vector<int> G[MAXN]; double mp[MAXN][MAXN]; int par[MAXN]; int rnk[MAXN]; double dist(int x1,int y1,int x2,int y2) { return sqrt(double((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))); } void prep(int n) { for(int i=0;i<=n;i++) { par[i]=i; rnk[i]=0; } } int fnd(int x) { if(par[x]==x) return x; return par[x]=fnd(par[x]); } void unite(int x,int y) { int a=fnd(x); int b=fnd(y); if(a==b) { return ; } if(rnk[a]<rnk[b]) { par[a]=b; } else { par[b]=a; if(rnk[a]==rnk[b]) rnk[a]++; } } bool judge(int n) { int f=fnd(1); for(int i=2;i<=n;i++) if(f!=par[i]) return false; return true; } double d[MAXN]; int vis[MAXN]; double prim(int s) { double ans=0; for(int i=1;i<=V;i++) { d[i]=INF; vis[i]=0; } d[s]=0; priority_queue<P,vector<P>,greater<P> > que; que.push(P(0,s)); while(!que.empty()) { P now=que.top();que.pop(); int v=now.second; if(vis[v]) continue; ans+=now.first; vis[v]=1; for(int i=0;i<G[v].size();i++) { int to=G[v][i]; if(d[to]>mp[v][to]) { d[to]=mp[v][to]; que.push(P(d[to],to)); } } } return ans; } int main() { int T; scanf("%d",&T); while(T--) { scanf("%d",&V); prep(V); for(int i=1;i<=V;i++) for(int j=1;j<=V;j++) if(i==j) mp[i][j]=0; else mp[i][j]=INF; for(int i=1;i<=V;i++) { scanf("%d%d",&ps[i].x,&ps[i].y); } for(int i=1;i<=V;i++) for(int j=i+1;j<=V;j++) { double co=dist(ps[i].x,ps[i].y,ps[j].x,ps[j].y); if(co<10||co>1000) continue; mp[i][j]=mp[j][i]=co; G[i].push_back(j); G[j].push_back(i); unite(i,j); } if(judge(V)) { double ans=prim(1); printf("%0.1lf\n",ans*100); } else { printf("oh!\n"); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/program-ccc/p/5159150.html