ZOJ 1914 Arctic Network (kruskal + prim )

 

 

KRUSKAL + PRIORITY_QUEUE

#include<iostream> #include<string> #include<queue> #include<cmath> #include<stack> using namespace std; struct edge { int from,to; int w; } t; int point[501][2],p[501]; int find(int i) { return p[i]==i?i:(p[i]=find(p[i])); } struct cmp { bool operator ()(const struct edge a,const struct edge b) { return a.w>b.w; } }; int main(void) { int cases,from,to,i,j; int satelite,n; double len; priority_queue<edge,vector<edge>,cmp> q; stack<int> qq; cin >> cases; while( cases-- ) { while( !q.empty() ) q.pop(); cin >> satelite >> n; for( i = 1; i <= n; i++ ) cin >> point[i][0] >> point[i][1]; for( i = 1; i <= n; i++ ) for( j = i+1; j <= n; j++ ) { t.from = i; t.to = j; t.w = (point[i][0]-point[j][0])*(point[i][0]-point[j][0]) + (point[i][1]-point[j][1])*(point[i][1]-point[j][1]); q.push(t); } while( !qq.empty() ) qq.pop(); for( i = 1; i<= n; i++ ) p[i] = i; while( !q.empty() ) { t = q.top();q.pop(); from = find( t.from ); to = find( t.to ); if( from == to ) continue; p[from] = to; qq.push(t.w); } while( --satelite ) qq.pop(); len = sqrt( qq.top() ); printf("%.2f/n",len); } return 0; }

 

 

PRIM+PRIORITY_QUEUE

 

#include<iostream> #include<string> #include<queue> #include<cmath> #include<stack> #include<cstring> using namespace std; const int M = 501; const int INF = 99999999; int mat[M][M],flag[M],dist[M]; int point[M][2]; typedef pair<int,int> pii; priority_queue<pii,vector<pii>,greater<pii> > q; priority_queue<int> qq; int main(void) { int cases,n,m; int i,j,now; cin >> cases; while( cases-- ) { while(!qq.empty() ) qq.pop(); memset(mat,0,sizeof(mat)); memset(flag,0,sizeof(flag)); cin >> m >> n; for( i = 1; i <= n; i++ ) cin >> point[i][0] >> point[i][1]; for( i = 1; i <= n; i++ ) for( j = i+1; j <= n; j++ ) mat[i][j] = mat[j][i]= (point[i][0]-point[j][0])*(point[i][0]-point[j][0]) + (point[i][1]-point[j][1])*(point[i][1]-point[j][1]); for( i =1; i <= n; i++ ) dist[i]=INF; dist[now=1] = 0; q.push( make_pair(0,1) ); while( !q.empty() ) { pii t = q.top();q.pop(); now = t.second; if( flag[now] ) continue; flag[now] = 1; qq.push(t.first); for( i = 1;i <= n; i++ ) if( !flag[i] && dist[i] > mat[now][i] && now !=i) { dist[i] = mat[now][i]; q.push( make_pair(dist[i],i) ); } } while( --m ) qq.pop(); printf("%.2f/n",sqrt( qq.top() )); } return 0; }

你可能感兴趣的:(ZOJ 1914 Arctic Network (kruskal + prim ))