#include<iostream>
#include <windows.h>
#define MAX 9
using namespace std;
template<class Type>
class NetGraph
{
private:
Type vexs[MAX];
int arc[MAX][MAX];
int numVertexes;
int numEdges;
int getPosition(Type el);
public:
NetGraph();
void print();
void ShortestPath_Dijkstra(int v0, int *P, int *D);
};
template<class Type>
int NetGraph<Type>::getPosition(Type el)
{
int i;
for (i = 0; i < this->numVertexes; i++)
{
if (this->vexs[i] == el)
return i;
}
return -1;
}
template<class Type>
NetGraph<Type>::NetGraph()
{
Type c1, c2;
int p1, p2;
int i, j;
int weight;
cout << "Input Vertexes number: ";
cin >> this->numVertexes;
cout << "Input Edges number: ";
cin >> this->numEdges;
if (this->numVertexes < 1 || this->numEdges<1 || this->numEdges>this->numVertexes*(this->numVertexes - 1))
{
cout << "Input invalid!" << endl;
return;
}
for (i = 0; i < this->numVertexes; i++)
{
cout << "Input a Type data(" << i + 1 << "): ";
cin >> this->vexs[i];
}
for (i = 0; i < this->numVertexes; i++)
{
for (j = 0; j < this->numVertexes; j++)
{
if (i == j)
this->arc[i][j] = 0;
else
this->arc[i][j] = 65535;
}
}
for (i = 0; i < this->numEdges; i++)
{
cout << "Input a arc: ";
cin >> c1;
cout << "Input a arc: ";
cin >> c2;
p1 = getPosition(c1);
p2 = getPosition(c2);
if (p1 == -1 || p2 == -1 || p1 == p2)
{
cout << "Input Egde error!" << endl;
return;
}
cout << "Input a weight: ";
cin >> weight;
this->arc[p1][p2] = weight;
this->arc[p2][p1] = weight;
}
}
template<class Type>
void NetGraph<Type>::print()
{
int i, j;
cout << "***********************************" << endl;
cout << "邻接矩阵:" << endl;
for (i = 0; i < this->numVertexes; i++)
{
for (j = 0; j < this->numVertexes; j++)
cout << this->arc[i][j] << "\t";
cout << endl;
}
}
template<class Type>
void NetGraph<Type>::ShortestPath_Dijkstra(int v0, int *P, int *D)
{
int v, w, k, min;
int final[MAX];
for (v = 0; v < this->numVertexes; v++)
{
final[v] = 0;
D[v] = this->arc[v0][v];
P[v] = 0;
}
final[v0] = 1;
D[v0] = 0;
for (v = 1; v < this->numVertexes; v++)
{
min = 65535;
for (w = 0; w < this->numVertexes; w++)
{
if (!final[w] && D[w] < min)
{
k = w;
min = D[w];
}
}
final[k] = 1;
for (w = 0; w < this->numVertexes; w++)
{
if (!final[w] && (min + this->arc[k][w] < D[w]))
{
D[w] = min + this->arc[k][w];
P[w] = k;
}
}
}
}
int main()
{
int i;
int P[MAX], D[MAX];
NetGraph<char> graph;
graph.print();
graph.ShortestPath_Dijkstra(0, P, D);
cout << "*********************" << endl;
for (i = 0; i < MAX; i++)
cout << D[i] << " ";
cout << endl;
cout << "*********************" << endl;
for (i = 0; i < MAX; i++)
cout << P[i] << " ";
cout << endl;
system("pause");
return 0;
}