#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
#define MAXNUM 9
int graph[MAXNUM][MAXNUM];
bool isVisited[MAXNUM];
int selected[MAXNUM];
int SumWeight=0;
int sum;
void display()
{
cout<<"sumWeight: "<<SumWeight<<endl;
int i,j;
for (i=0; i<sum; i++)
{
cout<<selected[i]<<":";
for (j=1; j<MAXNUM; j++)
if (-1==graph[selected[i]][j])
cout<<j<<" ";
cout<<endl;
}
}
void createGraph(int V1,int V2,int weight)
{
graph[V1][V2]=weight;
graph[V2][V1]=weight;
isVisited[V1]=true;
isVisited[V2]=true;
}
void inputGraph()//将图的结点读入
{
char ch;
int V1,V2,weight;
do
{
cin>>ch;
if (ch!='#')
V1=ch-'0';
else break;
cin>>V2;
cin>>weight;
createGraph(V1,V2,weight);
}
while (1);
}
void Prim()
{
int i,j,V1=0,V2=0,temp,k=1,m;
for (i=0; i<MAXNUM; i++)
if (isVisited[i]) sum++;
i=0;
while (isVisited[V1]==false) V1++;
if (V1>=MAXNUM) return;
selected[i++]=V1;
isVisited[V1]=false;
while (k<sum)
{
temp=999;
for(j=0;j<i;j++)
{
for (m=1;m<MAXNUM;m++)
{
if ((graph[selected[j]][m]>0)&&(isVisited[m])&&(graph[selected[j]][m]<temp))
{
temp=graph[selected[j]][m];
V1=selected[j];
V2=m;
}
}
}
isVisited[V2]=false;
SumWeight+=graph[V1][V2];
graph[V1][V2]=-1;
graph[V2][V1]=-1;
selected[i++]=V2;
k++;
}
}
int main()
{
cout<<"请输入各边的权值,以#结束:(格式:顶点1 顶点6 权值3),"<<endl;
memset(isVisited,0,sizeof(isVisited));
inputGraph();//将图的信息读入,创建图
Prim();
display();
return 0;
}
Prim算法
于 2018-07-17 10:55:35 首次发布