#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
#define MaxInt 32767
#define MVNum 100
typedef string VerTexType;
typedef double ArcType;
int n;
struct Edges
{
VerTexType Head;
VerTexType Tail;
ArcType lowcost;
int loc;
}Edge[99*50];
typedef struct
{
VerTexType vexs[MVNum];
ArcType arcs[MVNum][MVNum];
int vexnum,arcnum;
}AMGraph;
struct edge
{
int i;
int j;
}eds[MVNum];
void CreatUDN(AMGraph &G)
{
double w;
cin>>G.vexnum;
for(int k=0;k<G.vexnum;k++)
cin>>G.vexs[k];
cin>>G.arcnum;
n=G.arcnum;
for(int k=0;k<G.arcnum;k++)
{
cin>>eds[k].i>>eds[k].j;
}
for(int k=0;k<G.arcnum;k++)
{
cin>>w;
G.arcs[eds[k].i][eds[k].j]=w;
G.arcs[eds[k].j][eds[k].i]=w;
Edge[k].Head=G.vexs[eds[k].i];
Edge[k].Tail=G.vexs[eds[k].j];
Edge[k].loc=k;
Edge[k].lowcost=w;
}
}
bool cmp(struct Edges&s1,struct Edges&s2)
{
return s1.lowcost<s2.lowcost;
}
int LocateVex(AMGraph G,VerTexType v)
{
for(int i=0;i<G.vexnum;++i)
{
if(G.vexs[i]==v)
{
return i;
}
}
return -1;
}
//划分函数(快速排序)
int divide( vector<Edges> &A, int low, int high )
{
struct Edges pivotkey=A[low];
A[0]=A[low];
while(low<high)
{
while(low<high&&A[high].lowcost>=pivotkey.lowcost) --high;
A[low]=A[high];
while(low<high&&A[low].lowcost<=pivotkey.lowcost) ++low;
A[high]=A[low];
}
A[low]=A[0];
return low;//枢轴位置
}
//快速排序的实现(递归)
void QuickSort( vector<Edges> &A, int low, int high)
{
int pivotloc;
if(low<high)
{
pivotloc=divide(A,low,high);
QuickSort(A,low,pivotloc-1);
QuickSort(A,pivotloc+1,high);
}
}
//快速排序的实现(外壳)
void QSort( vector<Edges> &A )
{
QuickSort(A,1,A.size()-1);
}
//Kruskal算法
template<class TypeOfVer, class TypeOfEdge>
bool Kruskal(AMGraph G, struct Edges Edge[],TypeOfEdge &cost)
{
if(G.arcnum<n-1) return 0;
vector<Edges>A;
A.push_back(Edge[0]);
for(int k=0;k<n;k++)
{
A.push_back(Edge[k]);
}
QSort(A);
for(int k=0;k<n;++k)
{
cout<<A[k+1].lowcost<<' ';
}cout<<endl;
for(int k=0;k<n;++k)
{
cout<<A[k+1].loc<<" ";
}cout<<endl<<endl;
int i,j,v1,v2,vs1,vs2;
int Vexset[100];
for(i=0;i<G.arcnum;i++)
Vexset[i]=i;
for(i=0;i<G.arcnum;++i)
{
v1=LocateVex(G,A[i+1].Head);
v2=LocateVex(G,A[i+1].Tail);
vs1=Vexset[v1];
vs2=Vexset[v2];
if(vs1!=vs2)
{
cout<<"("<<A[i+1].Head<<","<<A[i+1].Tail<<"),"<<A[i+1].lowcost<<endl;
cost+=A[i+1].lowcost;
for(j=0;j<G.vexnum;++j)
{
if(Vexset[j]==vs2) Vexset[j]=vs1;
}
}
}cout<<endl;
return 1;
}
int main()
{
double cost=0;
bool mark;
string style;
cin>>mark;
cin>>style;
cout<<style<<endl;
AMGraph G;
CreatUDN(G);
for(int u=0;u<G.arcnum;++u)
{
cout<<Edge[u].lowcost<<' ';
}cout<<endl;
for(int u=0;u<G.arcnum;++u)
{
cout<<Edge[u].loc<<' ';
}cout<<endl<<endl;
bool sk=Kruskal<string,double>(G,Edge,cost);
cout<<cost<<endl;
return 0;
}
4 数据结构课程设计小组任务4:Kruskal算法的设计
最新推荐文章于 2024-06-15 09:15:00 发布