题目链接
思路:根据题意要使得图中不成环,那么删去边后剩下的图肯定就是一棵树,又因为要使得删去边的权值总和最大,就意味着剩下那棵树的权值总和要尽量小,毫无疑问剩下那棵树就是这幅图的最小生成树,所以直接求最小生成树就行了。
ac代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
using namespace std;
#define int long long
int head[105];
struct node {
int st, ed, val;
};
vector<node> ll;
bool cmp(node a, node b) {
return a.val < b.val;
}
int f(int a) {
if (head[a] == 0) return a;
else return head[a] = f(head[a]);
}
signed main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n, m; cin >> n >> m; int sum = 0;
for (int i = 0; i < m; i++) {
node q; int u, v, w; cin >> u >> v >> w;
q.st = u, q.ed = v, q.val = w; sum += w;
ll.push_back(q);
}
sort(ll.begin(), ll.end(), cmp);
int ret = 0;
for (int i = 0; i < m; i++) {
node g = ll[i];
if (f(g.st) != f(g.ed)) {
head[f(g.ed)] = f(g.st);
ret += g.val;
}
}
cout << sum - ret << endl;
return 0;
}