HDU2988 (Kruskal water), hdu2988kruskal water
As a matter of fact, I am not very interested in updating my blog and writing my questions. Tomorrow is the first online competition, and I hope it will be smooth.
I am writing this article because I plan to write all the basic algorithms so that I can take a test interview or something.
Starting from graph theory, there is a kind of unspeakable liking for graph theory.
HDU2988 is a Kruskal water question. Why does it use Kruskal? Because it has more than 200000 vertices, less edges, and sparse graphs.
The Kruska algorithm is very simple, that is, greedy. it traverses from the minimum weight value and checks the set to check whether the edge can form a loop, if not, it is added to the edge set of the Minimum Spanning Tree, and the minimum spanning tree (MST) is formed ).
Below is the code
/*************************************** * *******************> OS: linux 3.small-24-generic (Mint-17)> Author: yaolong> Mail: dengyaolong@yeah.net> Time: thursday, September 04, 2014 07:52:04 ************************************* * ********************/# include <iostream> # include <cstdio> # include <string> # include <vector> # include <algorithm> using namespace std; # define MAXN 220000int f [MAXN]; int find (int x) {if (X = f [x]) {return x;} return f [x] = find (f [x]);} struct Edge {int u, v, w; edge () {} Edge (int uu, int vv, int ww): u (uu), v (vv), w (ww) {} bool operator <(const Edge & e) const {return this-> w <e. w ;}}; int main () {vector <Edge> ve; int u, v, w; int n, m; while (scanf ("% d ", & n, & m), n | m) {ve. resize (m); int ans = 0; for (int I = 0; I <n; I ++) {f [I] = I;} while (m --) {scanf ("% d", & u, & V, & w); ans + = w; ve [m] = Edge (u, v, w);} sort (ve. begin (), ve. end (); for (vector <Edge >:: iterator itr = ve. begin (); itr! = Ve. end (); ++ itr) {int fu = find (* itr ). u), fv = find (* itr ). v); if (fu! = Fv) {f [fu] = fv; ans-= (* itr). w ;}} printf ("% d \ n", ans);} return 0 ;}
Hdu 1875 least spanning tree (Kruskal) CE explained, Daniel
Change the distance function name. This function has been defined.
Reference: www.cplusplus.com/..tance/