次小生成树

https://www.acwing.com/problem/content/1150/

次小生成树

\(定义:给一个带权的图,把图的所有生成树按权值从小到大排序,第二小的称为次小生成树.\)

求法
  • \(方法1:先求最小生成树,再枚举删去最小生成树的边求解,时间复杂度\ O(mlogm + nm).\)
  • \(方法2:先求最小生成树,然后依次枚举非树边,然后将该边加入树中,同时从树中去掉一条边,\\ 使得最终的图仍是一棵树.则一定可以求出次小生成树.\)
对于本题

\(先预处理两点之间的路径的最小值与严格次小值\)

  • \(若最大值==当前边权,则尝试替换严格次大值.\)
  • \(否则,替换掉最大值.\)
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 510, M = 10010;
int n, m;
struct Edge {
    int a, b, w;
    bool f; //记录是否为树边
    bool operator< (const Edge &t) const {
        return w < t.w;
    }
}edge[M];
int p[N];
int dist1[N][N], dist2[N][N];
int h[N], e[N * 2], w[N * 2], ne[N * 2], idx;

void add(int a, int b, int c) {
    e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}

int find(int x) {
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}

void dfs(int u, int fa, int m1, int m2, int d1[], int d2[]) {
    d1[u] = m1, d2[u] = m2;
    for (int i = h[u]; ~i; i = ne[i]) {
        int j = e[i];
        if (j != fa) {
            int td1 = m1, td2 = m2;
            if (w[i] > td1) td2 = td1, td1 = w[i];
            else if (w[i] < td1 && w[i] > td2) td2 = w[i];
            dfs(j, u, td1, td2, d1, d2);
        }
    }
}


int main() {
    IO;
    cin >> n >> m;
    memset(h, -1, sizeof h);
    for (int i = 0; i < m; ++i) {
        int a, b, c;
        cin >> a >> b >> c;
        edge[i] = {a, b, c};
    }
    sort(edge, edge + m);
    for (int i = 1; i <= n; ++i) p[i] = i;
    ll sum = 0;
    for (int i = 0; i < m; ++i) {
        int a = edge[i].a, b = edge[i].b, w = edge[i].w;
        int pa = find(a), pb = find(b);
        if (pa != pb) {
            p[pa] = pb;
            sum += w;
            add(a, b, w), add(b, a, w);
            edge[i].f = 1;
        }
    }

    for (int i = 1; i <= n; ++i) dfs(i, -1, -inf, -inf, dist1[i], dist2[i]);

    ll res = 1e18;
    for (int i = 0; i < m; ++i) 
        if (!edge[i].f) {
            int a = edge[i].a, b = edge[i].b, w = edge[i].w;
            ll t;
            if (w > dist1[a][b]) t = sum + w - dist1[a][b];
            else if (w > dist2[a][b]) t = sum + w - dist2[a][b];
            res = min(res, t);
        }
    
    cout << res << '\n';
    return 0;
}
posted @ 2021-02-15 17:07  phr2000  阅读(53)  评论(0编辑  收藏  举报