题意:
最大生成树
思路:
最大生成树
code:
#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #include<vector> #include<string> #include<queue> #include<map> #include<set> #include<cmath> using namespace std; #define INF 0x3f3f3f3f #define PI acos(-1.0) #define eps 1e-4 #define maxd 10e4 #define mem(a, b) memset(a, b, sizeof(a)) typedef pair<int,int> pii; typedef long long LL; //------------------------------ const int maxn = 1005; const int maxm = 20005; struct Edge{ int u,v,w; bool operator < (const Edge et) const{ return w > et.w; } }e[maxm]; int n,m; void init(){ int u,v,w; for(int i = 0; i < m; i++){ scanf("%d%d%d",&u,&v,&w); e[i].u = u; e[i].v = v; e[i].w = w; } } int p[maxn]; int find(int x){ if(x == p[x]) return p[x]; else return p[x] = find(p[x]); } void solve(){ sort(e, e+m); for(int i = 0; i <= n; i++) p[i] = i; int cnt = 1; LL ans = 0; for(int i = 0; i < m; i++){ int pu = find(e[i].u); int pv = find(e[i].v); if(pu != pv){ ans += e[i].w; p[pu] = pv; cnt++; } if(cnt == n){ break; } } if(cnt < n) printf("-1\n"); else cout << ans << endl; } int main(){ scanf("%d%d",&n,&m); init(); solve(); return 0; }
这道题没有题解一定是因为特太简单了T_T 我居然因为 ans += e[i].w 写错位置wa了一发 b l g l
时间: 2024-10-11 21:10:48