算是很基础的最小生成树了吧,我用kruskal做的,机器转了400多ms,说明写的不是很好,目前尚在入门,慢慢来。
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; struct n1 { int s,e,w; }; n1 path[2100000]; int father[2001]; int find(int i) { while(father[i]!=i) { i=father[i]; } return i; } bool cmp(n1 a,n1 b) { return a.w<b.w; } int kruskal(int v,int e) { int temp1,temp2,i,sum,num_bian; v--; i=sum=num_bian=0; sort(path+1,path+e+1,cmp); 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 juli(char *a,char *b) { int i,sum; sum=0; for(i=0;i<7;i++) { if(a[i]!=b[i]) sum++; } return sum; } int main() { int i,j,k,n; char kache[2001][8]; while(scanf("%d",&n)&&n!=0) { for(i=1;i<=n;i++) { scanf("%s",kache[i]); father[i]=i; } k=0; for(i=1;i<n;i++) for(j=i+1;j<=n;j++) { k++; path[k].s=i; path[k].e=j; path[k].w=juli(kache[i],kache[j]); } printf("The highest possible quality is 1/%d.\n",kruskal(n,k)); } }
原文地址:http://blog.csdn.net/chaoweilanmao/article/details/27565001