template<
class Type>
class NetGraph
{
private:
Type vexs[MAX];
int arc[MAX][MAX];
int numVertexes, numEdges;
int getPosition(Type el);
Type readType();
public:
NetGraph();
~NetGraph(){}
void print();
void MiniSpanTree_Prim();
};
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>
Type NetGraph<Type>::readType()
{
Type ch;
cout <<
"Input a edge data: ";
cin >> ch;
return ch;
}
template<
class Type>
NetGraph<Type>::NetGraph()
{
int i,j;
Type c1, c2;
int p1, p2;
int weight;
cout <<
"Input Vertexes number: ";
cin >>
this->numVertexes;
cout <<
"Input Edge number: ";
cin >>
this->numEdges;
if (
this->numVertexes <
1 ||
this->numEdges<
1 ||
this->numEdges>
this->numVertexes*(
this->numVertexes -
1))
{
cout <<
"Error input!" << 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++)
{
c1 = readType();
c2 = readType();
p1 = getPosition(c1);
p2 = getPosition(c2);
if (p1 == -
1 || p2 == -
1 || p1 == p2)
{
cout <<
"Earror Input!" << endl;
return;
}
cout <<
"Input a weight value: ";
cin >> weight;
this->arc[p1][p2] = weight;
this->arc[p2][p1] = weight;
}
}
template<
class Type>
void NetGraph<Type>::print()
{
cout <<
"******************************" << endl;
cout <<
"打印邻接矩阵" << endl;
int i, j;
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>::MiniSpanTree_Prim()
{
int min, i, j, k;
int adjvex[MAX];
int lowcost[MAX];
lowcost[
0] =
0;
adjvex[
0] =
0;
for (i =
1; i <
this->numVertexes; i++)
{
lowcost[i] =
this->arc[
0][i];
adjvex[i] =
0;
}
for (i =
0; i <
this->numVertexes; i++)
{
min =
65535;
j =
1; k =
0;
while (j <
this->numVertexes)
{
if (lowcost[j] !=
0 && lowcost[j] < min)
{
min = lowcost[j];
k = j;
}
j++;
}
cout <<
"(" << adjvex[k] <<
", " << k <<
") ";
lowcost[k] =
0;
for (j =
1; j <
this->numVertexes; j++)
{
if (lowcost[j] !=
0 &&
this->arc[k][j] < lowcost[j])
{
lowcost[j] =
this->arc[k][j];
adjvex[j] = k;
}
}
}
}
int main()
{
NetGraph<
char> graph;
graph.print();
graph.MiniSpanTree_Prim();
return 0;
}