标签:+= queue include scanf har set ack argc oid
Kruskal模板题,需要注意,这道题空间限制很严格,第一遍下意识的开了一个记录数组(因为一对节点之间允许多条路经,这里想着进行优化,不过弄巧成拙了,遇到了第一个MLE)
#include <iostream>
#include <algorithm>
#include <queue>
#include <string>
#include <vector>
#include <cstdio>
#include <cstring>
#include <string>
#include <stack>
#include <map>
#include <set>
using namespace std;
const int maxp= 55;
const int maxr= 1250;
struct Edge
{
int u, v, c;
Edge(int _u= 0, int _v= 0, int _c= 0) : u(_u), v(_v), c(_c) {}
bool operator < (const Edge &rhs) const
{
return c< rhs.c;
}
};
Edge G[maxr];
int fa[maxp];
void AddEdge(int i, int u, int v, int c)
{
G[i]= Edge(u, v, c);
}
int Find(int x)
{
if (x== fa[x]){
return x;
}
return fa[x]= Find(fa[x]);
}
int Kruskal(int n, int m)
{
sort(G, G+m);
int cnt= n, ans= 0;
for (int i= 0; i< m; ++i){
int u= G[i].u, v= G[i].v;
if (Find(u)== Find(v)){
continue;
}
ans+= G[i].c;
fa[fa[u]]= fa[fa[v]];
if (1== --cnt){
break;
}
}
return cnt > 1 ? -1 : ans;
}
int main(int argc, char const *argv[])
{
int p, r;
int u, v, c;
while (~scanf("%d", &p) && p){
scanf("%d", &r);
for (int i= 1; i<= p; ++i){
fa[i]= i;
}
for (int i= 0; i< r; ++i){
scanf("%d %d %d", &u, &v, &c);
AddEdge(i, u, v, c);
}
printf("%d\n", Kruskal(p, r));
}
return 0;
}
标签:+= queue include scanf har set ack argc oid
原文地址:https://www.cnblogs.com/Idi0t-N3/p/14646041.html