题意:给你一些边,把所有点连起来成树。若能连起来,求出边最大值的和。若不能输出-1;
由于给的是边kruskal比prim要方便。-1WA了好几发。
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 20000 + 10;
int pa[1000 + 10];
struct node
{
int x, y, cost;
bool operator < (const node &a) const
{
return cost > a.cost;
}
};
node edges[maxn];
int n, m;
int root(int x)
{
if(pa[x] != x)
pa[x] = root(pa[x]);
return pa[x];
}
bool same(int x, int y)
{
return root(x) == root(y);
}
void unite(int x, int y)
{
int fx = root(x);
int fy = root(y);
pa[fx] = fy;
}
void kruskal()
{
long long ans = 0;
for(int i = 0; i < m; i++)
{
if(!same(edges[i].x, edges[i].y))
{
ans += edges[i].cost;
unite(edges[i].x, edges[i].y);
}
}
int cnt = 0;
for(int i = 1; i <= n; i++)
{
if(pa[i] == i) cnt++;
}
printf("%lld\n", cnt > 1 ? -1 : ans);
}
int main()
{
while(scanf("%d%d", &n, &m) == 2)
{
for(int i = 0; i <= n; i++) pa[i] = i;
for(int i = 0; i < m; i++)
{
scanf("%d%d%d", &edges[i].x, &edges[i].y, &edges[i].cost);
}
sort(edges, edges + m);
kruskal();
}
return 0;
}