Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 months ago
2.5 kB
1
Indexable
Never
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>

using namespace std;

struct Edge {
    int u, v, weight;
};

struct DisjointSet {
    vector<int> parent, rank;

    DisjointSet(int n) {
        parent.resize(n);
        rank.resize(n, 0);
        for (int i = 0; i < n; i++) {
            parent[i] = i;
        }
    }

    int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }
    void unite(int x, int y) {
        int rootX = find(x);
        int rootY = find(y);
        if (rootX != rootY) {
            if (rank[rootX] < rank[rootY]) {
                parent[rootX] = rootY;
            } else if (rank[rootX] > rank[rootY]) {
                parent[rootY] = rootX;
            } else {
                parent[rootY] = rootX;
                rank[rootX]++;
            }
        }
    }
};

bool compareEdges(const Edge& a, const Edge& b) {
    return a.weight < b.weight;
}

vector<pair<int,int> > mst[3030];

int findMinimumSpanningTreeWeights(int n, int m, vector<Edge> edges) {
    sort(edges.begin(), edges.end(), compareEdges);
    
    int ans = 0;
    DisjointSet ds(n);

    for (int i = 0; i < m; i++) {
        int u = edges[i].u;
        int v = edges[i].v;
        int weight = edges[i].weight;

        if (ds.find(u) != ds.find(v)) {
            ds.unite(u, v);
            mst[u].push_back(make_pair(v,weight));
            mst[v].push_back(make_pair(u,weight));
            ans += weight;
        }

    }

    return ans;
}

int vis[3030];

int dfs(int u, int v)
{
    if(u == v)
    {
        for(int i = 0; i < 3030; i++)
            vis[i] = 0;
        return 0;
    }
    vis[u] = 1;
    for(int i = 0; i < mst[u].size(); i++)
    {
        if(vis[mst[u][i].first] == 0)
        {
            int a = dfs(mst[u][i].first, v);
            if(a != -1)
            {
                return max(a,mst[u][i].second);
            }
        }
    }
    return -1;
}

int main() {
    int n, m;
    cin >> n >> m;

    vector<Edge> edges(m);
    for (int i = 0; i < m; i++) {
        cin >> edges[i].u >> edges[i].v >> edges[i].weight;
    }

    int mstSize = findMinimumSpanningTreeWeights(n, m, edges);

    for (int i = 0; i < m; i++) {
        cout << mstSize + edges[i].weight - dfs(edges[i].u, edges[i].v) << endl;
    }

    return 0;
}
Leave a Comment