浙大数据结构习题笔记:Prim算法

Prim算法

具体算法见慕课
Prim算法不需要特殊建立并查集和堆,裸建更轻松。

#include 
#include 
#define INF 100000
#define MAX_VERTEX 105

typedef int Vertex;
int G[MAX_VERTEX][MAX_VERTEX];
int parent[MAX_VERTEX];    //并查集
int dist[MAX_VERTEX];
int Nv;
int Ne;
int sum;
using namespace std;
vector<Vertex> MST;

void build(){
	Vertex v1,v2;
	int w;
	cin>>Nv>>Ne;
	for(int i=1;i<=Nv;i++){
		for(int j=1;j<=Nv;j++)
			G[i][j] = 0;  // 初始化图 
		dist[i] = INF;   // 初始化距离
		parent[i] = -1;  // 初始化并查集 
	}
	for(int i=0;i<Ne;i++){
		cin>>v1>>v2>>w;
		G[v1][v2] = w;
		G[v2][v1] = w;
	}
}

void init(Vertex s)
{
    dist[s] = 0;
    MST.push_back(s);
    for(Vertex i=1;i<=Nv;i++){
        if(G[s][i]){
            dist[i] = G[s][i];
            parent[i] = s;
        }
    }
}

//寻找没有收录的dist中最小值
Vertex FindMin()
{
    int min = INF;
    Vertex x = -1;
    for(Vertex i=1;i<=Nv;i++){
        if(dist[i] && dist[i]<min){
            min = dist[i];
            x = i;
        }
    }
    return x;
}

void output()
{
    cout<<"Enter num: "<<endl;
    for(Vertex i=1;i<=Nv;i++){
        cout<<MST[i]<<" ";
    }
    cout<<endl;
    cout<<"Sum : "<<sum<<endl;
    cout<<"Tree :"<<endl;
    for(Vertex i=1;i<=Nv;i++){
        cout<<parent[i]<<" ";
    }
}

void Prim(Vertex s)
{
    init(s);
    while(1){
        Vertex v = FindMin();
        if(v == -1)
            break;
        sum += dist[v];
        dist[v] = 0;
        MST.push_back(v);
        for(Vertex w=1;w<=Nv;w++){
            if(G[v][w] && dist[w]){
                if(G[v][w] < dist[w]){
                    dist[w] = G[v][w];
                    parent[w] = v;
                }
            }
        }
    }
}

int main()
{
    build();
    Prim(1);
    output();
    return 0;
}

你可能感兴趣的:(数据结构)