思路分析
每个顶点都对结果有贡献,那么就分别考虑每个顶点——对于每个顶点来说,假设其相连的边按从大到小的权值排序后分别为e1,e2,e3,…,最优的方案就是e1与e2组合,e3与e4组合…这样,该顶点对结果的贡献值为e1+e3+e5+…。处理所有顶点,最终结果即为最终解。
可以证明该贪心算法的正确性。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <algorithm>
#include <cmath>
#include <map>
#include <iomanip>
#include <vector>
#define ll long long
using namespace std;
const int maxn = 1e3 + 10;
vector<int> ans[maxn];
int main() {
int n;
scanf("%d", &n);
for(int i = 0; i < n * (n - 1) / 2; i++) {
int a, b, w;
scanf("%d%d%d", &a, &b, &w);
a--, b--;
ans[a].push_back(w);
ans[b].push_back(w);
}
for(int i = 0; i < n; i++) {
sort(ans[i].begin(), ans[i].end());
}
ll res = 0;
for(int i = 0; i < n; i++) {
for(int j = n- 2; j >= 0; j-=2) {
res += ans[i][j];
//cout << ans[i][j] << " ";
}
//cout << endl;
}
printf("%lld\n", res);
}
UMS Online Judge