Hdu1102 Constructing Roads 【最小生成树】
http://acm.hdu.edu.cn/showproblem.php?pid=1102
Prim算法解决最短路问题
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <set> #include <map> #include <cmath> #include <queue> using namespace std; template <class T> void checkmin(T &t,T x) {if(x < t) t = x;} template <class T> void checkmax(T &t,T x) {if(x > t) t = x;} template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;} template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;} typedef pair <int,int> PII; typedef pair <double,double> PDD; typedef long long ll; #define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++) void checkmin(int &a,int b) { if(b < a) a = b; } void checkmax(int &a,int b) { if(b > a) a = b; } const int N = 111 , M = 22222; int dist[N] , n , m; bool vis[N]; queue <int > q; #define inf (1<<29) struct Edge { int v , w , next; Edge () {} Edge(int v,int w,int next) : v(v),w(w),next(next) {} }edge[M]; int E , head[N]; void init() { E = 0; memset(head,-1,sizeof(head)); } void addedge(int u,int v,int w) { edge[E] = Edge(v,w,head[u]); head[u] = E++; edge[E] = Edge(u,w,head[v]); head[v] = E++; } void prim() { int ans = 0; for(int i=1;i<=n;i++) dist[i] = inf , vis[i] = 0; dist[1] = 0; while(1) { int u = -1 , Min = inf; for(int i=1;i<=n;i++) { if(!vis[i] && (u==-1 || dist[i] < Min) ) { Min = dist[i] ; u = i; } } if(u == -1) break; vis[u] = 1; ans += dist[u]; for(int i=head[u];i!=-1;i=edge[i].next) { int v = edge[i].v; if(!vis[v]) checkmin(dist[v] , edge[i].w); } } printf("%d\n" , ans); } int main() { while(~scanf("%d",&n)) { init(); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { int w; scanf("%d",&w); if(i < j) addedge(i , j , w); } scanf("%d",&m); while(m --) { int u , v; scanf("%d%d",&u,&v); addedge(u , v , 0); } prim(); } return 0; }

浙公网安备 33010602011771号