HDU1863-unblocked Project: http://acm.hdu.edu.cn/showproblem.php?pid=1863
This question I use and check the method at noon AC once, afternoon learned prim. Another pose, one more time = =!
And the method of checking the set: http://blog.csdn.net/p_rogrammer/article/details/47979073
Code:
#include <iostream> #include <cstdio> #include <vector> #include <cstring>using namespace std; const int MAXN = 111;const int Inf = 1<<31-1;int n,m;int x,y,z;vector<int>mapp[maxn];int cost[maxn][maxn],vi S[maxn],distance[maxn];void Initial () {for (int i = 0;i < maxn;i++) mapp[i].clear (); Fill (Vis,vis + maxn,0); Fill ( Distance,distance + Maxn,inf);} int Prim () {int ans = 0, cnt = 0;distance[1] = 0; while (true) {int v = -1;//Every time you start from the first village, look for the number of villages nearest the village that has been connected. V for (int i = 1;i <= m;i++) if (!vis[i] && (v = =-1 | | Distance[i] < distance[v]) v = i;//printf ("v =%d\n", v); if (v = =-1 | | DISTANCE[V] = = Inf) return-1; Ans + = distance[v];//printf ("ans =%d\n", ans); cnt++;//the number of villages that have been joined together if (cnt = = M) return ans; Vis[v] = 1;//Village v mark for access over//printf ("vis[%d] =%d\n", v,vis[v]); for (int i = 0;i < Mapp[v].size (); i++) {int x = mapp[v][i];//x is the village number connected to V if (!vis[x] && cost[v][x] < Distance [x]) DISTANCE[X] = cost[v][x];//update to the distance of the connected village, guaranteed to be the shortest}}}int main() {while (~SCANF ("%d", &n) && N) {scanf ("%d", &m), Initial (); while (n--) {scanf ("%d%d%d", &x,&y, &Z); if (x! = y) {mapp[x].push_back (y); Mapp[y].push_back (x); Cost[x][y] = cost[y][x] = z;//graph, x can be y,y to X, on with}}int flag = Prim (), if (flag = =-1) printf ("\ n"), Else printf ("%d\n", flag); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Prim minimum spanning tree algorithm for HDU1863-unblocked engineering