TheAlgorithms-C-Plus-Plus/Greedy Algorithms/Prims Minimum Spanning Tree.cpp

83 lines
1.2 KiB
C++
Raw Normal View History

2017-02-27 17:50:03 +08:00
#include <iostream>
using namespace std;
2017-02-27 02:33:23 +08:00
#define V 4
2017-02-27 17:50:03 +08:00
#define INFINITY 99999
int graph[V][V] = {
{0, 5, 1, 2},
{5, 0, 3, 3},
{1, 3, 0, 4},
{2, 3, 4, 0}
};
2017-02-27 02:33:23 +08:00
2017-02-27 17:50:03 +08:00
struct mst
2017-02-27 02:33:23 +08:00
{
2017-02-27 17:50:03 +08:00
bool visited;
int key;
int near;
};
2017-02-27 02:33:23 +08:00
2017-02-27 17:50:03 +08:00
mst MST_Array[V];
2017-02-27 02:33:23 +08:00
2017-02-27 17:50:03 +08:00
void initilize()
{
for (int i = 0; i < V; i++)
{
MST_Array[i].visited=false;
MST_Array[i].key=INFINITY; // considering INFINITY as inifinity
MST_Array[i].near=i;
}
MST_Array[0].key=0;
2017-02-27 02:33:23 +08:00
}
2017-02-27 17:50:03 +08:00
void updateNear()
2017-02-27 02:33:23 +08:00
{
2017-02-27 17:50:03 +08:00
for (int v = 0; v < V; v++)
{
int min=INFINITY;
int minIndex=0;
for (int i = 0; i < V; i++)
{
if (MST_Array[i].key<min && MST_Array[i].visited==false && MST_Array[i].key!=INFINITY)
{
min=MST_Array[i].key;
minIndex=i;
}
}
MST_Array[minIndex].visited=true;
for (int i = 0; i < V; i++)
{
if (graph[minIndex][i]!=0 && graph[minIndex][i]<INFINITY)
{
if (graph[minIndex][i]<MST_Array[i].key)
{
MST_Array[i].key=graph[minIndex][i];
MST_Array[i].near=minIndex;
}
}
}
}
2017-02-27 02:33:23 +08:00
}
2017-02-27 17:50:03 +08:00
void show()
2017-02-27 02:33:23 +08:00
{
for (int i = 0; i < V; i++)
{
2017-02-27 17:50:03 +08:00
cout<<i<<" - "<<MST_Array[i].near<<"\t"<<graph[i][MST_Array[i].near]<<"\n";
2017-02-27 02:33:23 +08:00
}
}
int main()
{
2017-02-27 17:50:03 +08:00
initilize();
updateNear();
show();
2017-02-27 02:33:23 +08:00
return 0;
}