And deeply understand again prim and Dijkstra algorithm, feel pretty good ~
The first time I write with the adjacency table, just soso~ AH ~
First by priority queue, overloaded operator to get stuck ~ Egg ache ~
1#include <iostream>2#include <cstdio>3#include <cstdlib>4#include <cstring>5#include <string>6#include <queue>7#include <algorithm>8#include <map>9#include <iomanip>Ten#include <climits> One#include <string.h> A#include <stdlib.h> -#include <vector> - #defineINF 1e7 the #defineMAXN 111111 - using namespacestd; - - + structnode{ - intV, W; + BOOL operator< (Constnode& a)Const { A returnW >A.W; at } - }; - -Vector<node>G[MAXN]; - BOOLVIS[MAXN]; - intDIS[MAXN]; in intN, M; -Priority_queue<node>Q; to + - voidPrim (node s) the { *memset (Vis,0,sizeof(Vis)); $ for(inti =0; I <= N; ++i) Dis[i] =INF;Panax Notoginseng while(!q.empty ()) Q.pop (); - intAns =0; the Q.push (s); + while(!Q.empty ()) { ANode U =q.top (); the Q.pop (); + if(VIS[U.V])Continue; -VIS[U.V] =true; $Ans + =U.W; $ //cout << ans << endl; - for(inti =0; I < g[u.v].size (); ++i) { - intv =g[u.v][i].v; the if(!vis[v] && dis[v] >G[U.V][I].W) { -DIS[V] =G[U.V][I].W;Wuyi Q.push ({V, dis[v]}); the } - } Wu } -cout << ans <<Endl; About } $ - - intMain () - { A intA, B, C; +CIN >> N >>m; the for(inti =1; I <= m; ++i) { -Cin >> a >> b >>C; $ G[a].push_back ({b, C}); the G[b].push_back ({A, c}); the } thePrim ({1,0 }); the //System ("pause"); - return 0; in}
Prim algorithm for Hihocoder 29th Zhou Yi Optimization