依旧是最小生成树的基础题~
#include<iostream> #include<algorithm> using namespace std; int father[101]; struct n1 { int s,e,w; }; n1 path[6000]; bool cmp(n1 a,n1 b) { return a.w<b.w; } int find(int i) { while(father[i]!=i) { i=father[i]; } return i; } int kruskal(int v,int e) { int temp1,temp2,i,sum,num_bian; for(i=1;i<=v;i++) { father[i]=i; } sort(path+1,path+e+1,cmp); i=sum=num_bian=0; v--; while(num_bian!=v) { i++; temp1=find(path[i].s); temp2=find(path[i].e); if(temp1!=temp2) { sum+=path[i].w; num_bian++; if(temp1>temp2) { temp1^=temp2^=temp1^=temp2; } father[temp2]=temp1; } } return sum; } int main() { int t,i,j,k,map[101][101],n; while(scanf("%d",&n)!=EOF){ k=0; for(i=1;i<=n;i++) for(j=1;j<=n;j++) { scanf("%d",&map[i][j]); if(j>i) { k++; path[k].s=i; path[k].e=j; path[k].w=map[i][j]; } } printf("%d\n",kruskal(n,k)); } }
poj1258
时间: 2024-10-18 02:50:38