POJ 2485 Highways (kruskal+prim)

题目让求使所有点都连通的树的最大边最小的那棵树,的最大边。。。有点拗口,就是求哪棵树的最大边最小。。。求出最大边。

 

可以转换成,求最小生成树的最大边,因为kruskal中每次加到树中的边都是最小的。

 

另外,在prim算法中,我用到了在《算法艺术与信息学竞赛--算法竞赛入门经典》上看到的方法,用vector数组来表示图,用pair来方便比较,有意者可看204页的详细说明。

 

kruskal:

#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; struct node { int from,to,w; } edge[250000],t; int p[501]; int cmp(const node a,const node b) {return a.w<b.w;} int find(int i) {return i==p[i]?i:p[i]=find(p[i]);} int main(void) { int cases,n; int i,j,count; int from,to,max; scanf("%d",&cases); while( cases-- ) { scanf("%d",&n); for( i = 1,count = 0; i <= n; i++ ) for( j = 1; j <= n; j++ ) { t.from = i; t.to = j; scanf("%d",&t.w); if( i == j ) continue; count++; edge[count] = t; } for( i = 1; i <= n; i++ ) p[i] = i; sort(edge+1,edge+1+count,cmp); for( i = 1,max = -1; i <= count; i++ ) { from = edge[i].from;to = edge[i].to; from = find(from);to = find(to); if( from == to ) continue; p[from] = to; if( edge[i].w > max ) max = edge[i].w; } printf("%d/n",max); } return 0; }

 

prim:

 

#include<cstdio> #include<iostream> #include<queue> #include<vector> using namespace std; const int INF = 99999999; typedef pair<int,int> pii; vector<pii> G[501]; priority_queue< pii,vector<pii>,greater<pii> > q; int main(void) { int cases,n; int i,j,k; int max,from,to,w; int dist[501],flag[501]; scanf("%d",&cases); while( cases-- ) { scanf("%d",&n); for( i = 1; i <= n; i++ ) { G[i].clear(); dist[i] = INF; flag[i] = 0; } for( i = 1; i <= n; i++ ) for( j = 1; j <= n; j++ ) { scanf("%d",&w); if( w == 0 || i == j ) continue; G[i].push_back(make_pair(w,j)); } while( !q.empty() ) q.pop(); q.push(make_pair(0,1)); max = -1;dist[1] = 0; while( !q.empty() ) { pii u = q.top();q.pop(); to = u.second; if( flag[to] ) continue; flag[to] = 1; w = u.first; if( w > max ) max = w; for( i = 0; i < G[to].size(); i++ ) { pii a = G[to][i]; if( dist[a.second] > a.first ) { dist[a.second] = a.first; q.push(G[to][i]); } } } printf("%d",max); } return 0; }

 

你可能感兴趣的:(POJ 2485 Highways (kruskal+prim))