标签:include map algorithm hdu print getch 最小生成树 struct har
普里姆求解:
#include<cstdio> #include<cmath> #include<cstring> #include<iostream> #include<cstdlib> #include<algorithm> #include<string> #include<stack> #include<queue> #include<map> using namespace std; const int MAX=100; const int INF=100000; int n;//村庄数 int G[MAX][MAX],d[MAX]; bool isVisit[MAX]={false}; int prim(){ fill(d,d+MAX,INF); d[0]=0; int ans=0; for(int i=0;i<n;i++){ int u=-1,MIN=INF; for(int j=0;j<n;j++){ if(isVisit[j]==false&&d[j]<MIN){ u=j; MIN=d[j]; } } if(u==-1) return -1; isVisit[u]=true; ans+=d[u]; for(int v=0;v<n;v++){ if(isVisit[v]==false&&G[u][v]!=INF&&d[v]>G[u][v]){ d[v]=G[u][v]; } } } return ans; } int main(){ while(scanf("%d",&n)&&n!=0){ getchar(); fill(G[0],G[0]+MAX*MAX,INF); int temp1,temp2; char c1[10],c2[10]; for(int i=0;i<n-1;i++){ scanf("%s %d",&c1,&temp1); for(int j=0;j<temp1;j++){ scanf("%s %d",&c2,&temp2); G[c1[0]-‘A‘][c2[0]-‘A‘]=G[c2[0]-‘A‘][c1[0]-‘A‘]=temp2; } } int ans=prim(); printf("%d\n",ans); } return 0; }
-克鲁斯卡尔:
#include<cstdio> #include<cmath> #include<cstring> #include<iostream> #include<cstdlib> #include<algorithm> #include<string> #include<stack> #include<queue> #include<map> using namespace std; const int MAX=100; const int MAXE=100; const int INF=1000000000; int d[MAX],father[MAX]; int n,m=0; bool isVisit[MAX]={false}; struct edge{ int node1,node2; int weight; }E[MAXE]; bool cmp(edge e1,edge e2){ return e1.weight<e2.weight; } int findFather(int x){ int a=x; while(x!=father[x]){ x=father[x]; } while(a!=father[a]){ int temp=a; a=father[a]; father[temp]=x; } return x; } int kruskal(){ int ans=0,num_edge=0; for(int i=0;i<n;i++) father[i]=i; sort(E,E+m,cmp); for(int i=0;i<m;i++){ int f1=findFather(E[i].node1); int f2=findFather(E[i].node2); if(f1!=f2){ father[f1]=f2; ans+=E[i].weight; num_edge++; //边数等于顶点数-1结束 if(num_edge==n-1) break; } } if(num_edge!=n-1) return -1; else return ans; } int main(){ while(scanf("%d",&n)&&n!=0){ getchar(); //fill(G[0],G[0]+MAX*MAX,INF); char c1[10],c2[10]; int temp1,temp2; for(int i=0;i<n-1;i++){ scanf("%s %d",&c1,&temp1); for(int j=0;j<temp1;j++){ scanf("%s %d",&c2,&temp2); E[m].node1=c1[0]-‘A‘; E[m].node2=c2[0]-‘A‘; E[m].weight=temp2; m++; } } int ans=kruskal(); printf("%d\n",ans); } return 0; }
hduoj-1301 Jungle Roads(最小生成树-克鲁斯卡尔和普里姆求解)
标签:include map algorithm hdu print getch 最小生成树 struct har
原文地址:https://www.cnblogs.com/anhuixuyin218/p/8794344.html