[USACO 102]Agri-Net

时间:2023-02-03 07:06:32

OJ题号:POJ1258、洛谷1546

思路:Kruskal。

 #include<cstdio>
#include<utility>
#include<vector>
#include<algorithm>
#define w first
#define a second.first
#define b second.second
typedef std::pair<int,std::pair<int,int> > Edge;
const int N=;
int n;
std::vector<Edge> e;
class UnionFindSet {
private:
int anc[N];
public:
UnionFindSet(int n) {
for(int i=;i<n;i++) anc[i]=i;
}
int Find(int x) {
return (x==anc[x])?x:(anc[x]=Find(anc[x]));
}
void Union(int x,int y) {
anc[Find(y)]=Find(x);
}
};
int main() {
scanf("%d",&n);
for(int i=;i<n;i++) {
for(int j=;j<n;j++) {
int c;
scanf("%d",&c);
if(i<j) {
e.push_back(std::make_pair(c,std::make_pair(i,j)));
}
}
}
UnionFindSet s(n);
std::sort(e.begin(),e.end());
int ans=;
for(int i=;i<(int)e.size();i++) {
if(s.Find(e[i].a)==s.Find(e[i].b)) continue;
ans+=e[i].w;
s.Union(e[i].a,e[i].b);
}
printf("%d\n",ans);
return ;
}