Agri-Net
题目链接:
http://poj.org/problem?id=1258
解题思路:
最小生成树!!!
不懂的,建议看看这个人的博客:http://www.cnblogs.com/biyeymyhjob/archive/2012/07/30/2615542.html
AC代码(kruskal):
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100010;
int pa[maxn];
int n,m,sum;
struct Edge{
int u,v,w;
}edge[maxn];
bool cmp(Edge a,Edge b){
return a.w < b.w;
}
int Find(int x){
if(pa[x] != x)
pa[x] = Find(pa[x]);
return pa[x];
}
int kruskal(){
int u,v,cnt = n,l=0;
for(int i = 0; i < sum; i++){
u = Find(edge[i].u);
v = Find(edge[i].v);
if(u != v){
l += edge[i].w;
pa[v] = u;
if(--cnt == 1)
break;
}
}
return l;
}
int main(){
int n;
while(scanf("%d",&n)!=EOF){
memset(pa,-1,sizeof(pa));
int w;
sum = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++){
scanf("%d",&w);
if(i != j){
edge[sum].u = i;
edge[sum].v = j;
edge[sum++].w = w;
}
}
for(int i = 0; i < sum; i++)
pa[i] = i;
sort(edge,edge+sum,cmp);
printf("%d\n",kruskal());
}
return 0;
}
AC代码(prim):
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int INF = 0xfffffff;
int maze[110][110];
int vis[110],n;
int prime(){
int tmp = 0,sum = 0;
vis[0] = 1;
for(int i = 1; i < n; i++){
int minn = INF;
for(int j = 0; j < n; j++)
if(vis[j]){
for(int k = 0; k < n; k++){
if(!vis[k] && maze[j][k]<minn)
minn=maze[j][k],tmp=k;
}
}
sum += minn;
vis[tmp] = 1;
}
return sum;
}
int main(){
while(scanf("%d",&n)!=EOF){
memset(maze,0,sizeof(maze));
memset(vis,0,sizeof(vis));
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
scanf("%d",&maze[i][j]);
printf("%d\n",prime());
}
return 0;
}