最小生成樹prim普里姆演算法

二零二一發表於2020-11-25

**標頭檔案

#pragma once
#include<stdio.h>
#include<stdlib.h>
#define OVERFLOW -2
#define INFINITY 1000 //無窮大
#define MN 6 //圖的頂點數目
typedef char vertexType;
typedef int arcType;

原始碼

#include"c1.h"

typedef struct {
	vertexType vexs[MN];
	arcType arcs[MN][MN];
	int vexnum, arcnum; // 頂點數和邊數
}MGraph;

MGraph G;

typedef struct{
	int fromvex, tovex;
	int cost;
}MST[MN- 1];  // 邊的儲存結構

MST T; //存放G的最小生成樹,作為prim的輸出

void CreateMGraph() {
	int i, j, k, c;
	printf("請輸入圖的頂點數目和邊的數目: ");
	scanf_s("%d%d", &G.vexnum, &G.arcnum);
	getchar();  //收集垃圾 Enter鍵
	printf("輸入圖的各項點資訊: \n");
	for (i = 0; i < G.vexnum; i++)
		scanf_s("%c", &G.vexs[i]);
	for (i = 0; i < G.vexnum; i++)
		for (j = 0; j < G.vexnum; j++)
			G.arcs[i][j] = INFINITY;
	for (k = 0; k < G.arcnum; k++) {

		printf("請輸入第%d條邊的兩個端點的序號及權值(i,j,c): ", k + 1);
		scanf_s("%d,%d,%d", &i, &j, &c);
		G.arcs[i][j] = c;
		G.arcs[j][i] = c;

	}
}
void InitCondidateSet(MGraph G,int r) {
	
	int i, k = 0;
	for (i = 0; i < G.arcnum; i++)
	{
		if (i != r) {
			T[k].fromvex = r;
			T[k].tovex = i;
			T[k].cost = G.arcs[r][i];
			k++;
		}
	}
}
int SelectLightEdge(int k)
{
	int min = INFINITY, minpos = 0;;
	for(int i = k;i<MN-1;i++)
		if (T[i].cost < min) {
			min = T[i].cost;
			minpos = i;
		}
	return minpos;
}
void ModifySet(int k, int v) {
	int d;
	for (int i = k; i < MN - 1; i++) {
		d = G.arcs[v][T[i].tovex];

		if (d < T[i].cost) {
			T[i].cost = d;
			T[i].fromvex = v;
		}
	}
}
void primMST(MGraph G, int r) {
	int m,v;
	MST e;
	InitCondidateSet(G, r);
	for (int k = 0; k < MN - 1; k++) {
		m = SelectLightEdge(k);
		e[0] = T[m];
		T[m] = T[k];
		T[k] = e[0];
		v = T[k].tovex;
		ModifySet(k + 1, v);
	}
}
int main()
{
	int num;
	CreateMGraph();
	printf("請輸入第一個項點的序號: ");
	scanf_s("%d",&num);
	primMST(G, num);
	for (int i = 0; i < MN - 1; i++)
	{
		printf("第%d條邊:V%d----V%d; 權值為%d\n", i + 1, T[i].fromvex, T[i].tovex, T[i].cost);
	}
	system("pause");
	return 0;

相關文章