problemscpp
A collection of my answers to algorithm problems in c++.
| 函数
acwing::acwing858_408 命名空间参考

  1. Prim算法求最小生成树
更多...

struct  pair_equal
 
struct  pair_hash
 
struct  tuple_compare
 

函数

int main (istream &cin, ostream &cout)
 
 TEST (acwing858_408, case1)
 

详细描述

  1. Prim算法求最小生成树

函数说明

◆ main()

int acwing::acwing858_408::main ( istream &  cin,
ostream &  cout 
)

在文件 acwing408.cpp712 行定义.

712 {
713 int n, m;
714 int ans = 0;
715 unordered_set<int> mst;
716 unordered_map<int, unordered_set<pair<int, int>, pair_hash, pair_equal>> g;
717 priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, tuple_compare> pq;
718 cin >> n >> m;
719 while(m--) {
720 int u, v, w;
721 cin >> u >> v >> w;
722 if(g.find(u) == g.end()) {
723 g[u] = unordered_set<pair<int, int>, pair_hash, pair_equal>();
724 }
725 g[u].insert(make_pair(v, w));
726 if(g.find(v) == g.end()) {
727 g[v] = unordered_set<pair<int, int>, pair_hash, pair_equal>();
728 }
729 g[v].insert(make_pair(u, w));
730 }
731 mst.insert(g.begin()->first);
732 for(const auto &p: g[g.begin()->first]) {
733 pq.push(make_tuple(g.begin()->first, p.first, p.second));
734 }
735 while(!pq.empty()) {
736 auto [u, v, w] = pq.top();
737 pq.pop();
738 bool u_in = mst.find(u) != mst.end();
739 bool v_in = mst.find(v) != mst.end();
740 if(u_in && v_in)
741 continue;
742 int to_insert = u_in ? v : u;
743 mst.insert(to_insert);
744 ans += w;
745 for(const auto &p: g[to_insert]) {
746 if(mst.find(p.first) != mst.end() && mst.find(to_insert) != mst.end())
747 continue;
748 pq.push(make_tuple(to_insert, p.first, p.second));
749 }
750 }
751 if(mst.size() == n) {
752 cout << ans;
753 } else {
754 cout << "impossible";
755 }
756 return 0;
757 }

被这些函数引用 TEST().

◆ TEST()

acwing::acwing858_408::TEST ( acwing858_408  ,
case1   
)

在文件 acwing408_test.cpp1132 行定义.

1132 {
1133 istringstream in("4 5\n"
1134 "1 2 1\n"
1135 "1 3 2\n"
1136 "1 4 3\n"
1137 "2 3 2\n"
1138 "3 4 4");
1139 auto out = ostringstream();
1140 main(in, out);
1141 const auto ans = out.str();
1142 ASSERT_EQ("6", ans);
1143 }
int main(int argc, char **argv)
Definition: main.cpp:5

引用了 main().