c_cpp Prim的MST

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp Prim的MST相关的知识,希望对你有一定的参考价值。

// priority_queue is a max-heap by default, but often we want the smallest item
// at the top, rather than the largest.  If so, note the following syntax to
// define our priority_queue.
priority_queue<ii, vector<ii>, greater<ii>> pq;
vi vis;
vector<vii> g;

// Helper function for processing a node 'u', marking it as visited, then taking
// all direct neighbors of 'u', which have not been visited, and pushing them
// into the priority_queue.  When doing Prim's, we would need this logic in two
// places (note: pqUtil(0) for first, then each after mst += ...), so it makes
// sense to put this logic into its own function
void pqUtil(int u) {
  vis[u] = 1;
  for (auto &t : g[u]) {
    int v = t.second, w = t.first;
    if (!vis[v]) {
      pq.push(t);
    }
  }
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);

  int V, E;
  while (cin >> V >> E && (V || E)) {

    g.assign(V, vii());

    int u, v, w, tot = 0;
    REP(i, E) {
      cin >> u >> v >> w;
      g[u].push_back(ii(w, v));
      g[v].push_back(ii(w, u));
      tot += w;
    }

    // Prim's MST, O(V log E)
    pq.empty();
    vis.assign(V, 0);
    int mst = 0;
    pqUtil(0);

    while (!pq.empty()) {
      auto t = pq.top();
      pq.pop();
      if (!vis[t.second])
        mst += t.first, pqUtil(t.second);
    }
    cout << tot - mst << endl;
  }

  return 0;
}

以上是关于c_cpp Prim的MST的主要内容,如果未能解决你的问题,请参考以下文章

使用 Prim 和堆计算 MST 的总重量

找到 MST 的关键边:可以使用修改后的 Prim 算法吗?

MST-prim

我的 Prim 算法 (MST) 在矩阵中比在列表中运行得快得多

如何在 Haskell 中编写 MST 算法(Prim 或 Kruskal)?

贪心算法之prim算法的证明