This idea is also very simple, is to use a maximum heap to maintain the prim algorithm in the low array, the operation of refreshing the low array into a refresh heap operation, due to the heap insert operation bit LOGN, the query time is constant, so in the case of edge sparse, its complexity and kruscal close. This problem just started always WA, thought for a long time, do not know where the wrong, and later found that it is not possible to go directly to the minimum path in the heap, because the path of another endpoint may have been used.
Then finally found, AC.
In addition, this problem can be directly used Priority_queue, the code will be much less.
Impl:
1 intN, E;2vector<pair<int,int> > vertices[100010];3vector<pair<int,int> >edges;4 BOOLused[100010];5 6 BOOLCMP (pair<int,int> &p1, pair<int,int> &p2) {7 returnP1.second >P2.second;8 }9 TenUnsignedLong LongPrim () One { AUnsignedLong Longres =0; - intn = n-1; -used[1] =true; the for(size_t j =0; J < vertices[1].size (); ++j) -Edges.push_back (vertices[1][j]); - make_heap (Edges.begin (), Edges.end (), CMP); - + while(n--) { - while(used[edges[0].first]) {//remove the vertices that have been used, and don't forget + pop_heap (Edges.begin (), Edges.end (), CMP); A Edges.pop_back (); at } -pair<int,int> Minedge = edges[0]; -Res + =Minedge.second; -Used[minedge.first] =true; - pop_heap (Edges.begin (), Edges.end (), CMP); - Edges.pop_back (); in - for(size_t i =0; I < vertices[minedge.first].size (); ++i) { to if(!Used[vertices[minedge.first][i].first]) { + Edges.push_back (Vertices[minedge.first][i]); - push_heap (Edges.begin (), Edges.end (), CMP); the } * } $ }Panax Notoginseng - returnRes; the } + A intMain () the { + intu, V, W; -scanf"%d%d", &n, &E); $ for(inti =0; i < E; ++i) $ { -scanf"%d%d%d", &u, &v, &W); - Vertices[u].push_back (Make_pair (V, W)); the Vertices[v].push_back (Make_pair (U, W)); - }Wuyi theprintf"%d\n", Prim ()); - return 0; Wu}View Code
Hihocoder (1109) prim algorithm for heap optimization