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},
|
2019-08-21 10:10:08 +08:00
|
|
|
{2, 3, 4, 0}};
|
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++)
|
|
|
|
{
|
2019-08-21 10:10:08 +08:00
|
|
|
MST_Array[i].visited = false;
|
|
|
|
MST_Array[i].key = INFINITY; // considering INFINITY as inifinity
|
|
|
|
MST_Array[i].near = i;
|
2017-02-27 17:50:03 +08:00
|
|
|
}
|
|
|
|
|
2019-08-21 10:10:08 +08:00
|
|
|
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++)
|
|
|
|
{
|
2019-08-21 10:10:08 +08:00
|
|
|
int min = INFINITY;
|
|
|
|
int minIndex = 0;
|
2017-02-27 17:50:03 +08:00
|
|
|
for (int i = 0; i < V; i++)
|
|
|
|
{
|
2019-08-21 10:10:08 +08:00
|
|
|
if (MST_Array[i].key < min && MST_Array[i].visited == false && MST_Array[i].key != INFINITY)
|
2017-02-27 17:50:03 +08:00
|
|
|
{
|
2019-08-21 10:10:08 +08:00
|
|
|
min = MST_Array[i].key;
|
|
|
|
minIndex = i;
|
2017-02-27 17:50:03 +08:00
|
|
|
}
|
|
|
|
}
|
2019-08-21 10:10:08 +08:00
|
|
|
|
|
|
|
MST_Array[minIndex].visited = true;
|
|
|
|
|
2017-02-27 17:50:03 +08:00
|
|
|
for (int i = 0; i < V; i++)
|
|
|
|
{
|
2019-08-21 10:10:08 +08:00
|
|
|
if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY)
|
2017-02-27 17:50:03 +08:00
|
|
|
{
|
2019-08-21 10:10:08 +08:00
|
|
|
if (graph[minIndex][i] < MST_Array[i].key)
|
2017-02-27 17:50:03 +08:00
|
|
|
{
|
2019-08-21 10:10:08 +08:00
|
|
|
MST_Array[i].key = graph[minIndex][i];
|
|
|
|
MST_Array[i].near = minIndex;
|
2017-02-27 17:50:03 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
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++)
|
|
|
|
{
|
2019-08-21 10:10:08 +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;
|
|
|
|
}
|