#include
#include
using namespace std;
enum GraphType { undigraph, digraph, undinetwork, dinetwork };
template
struct EdgeType
{
T head, tail;
int cost;
};
template
struct Edge
{
T adjvex;
float lowcost;
};
template
class MGraph
{
private:
int vexnum, edgenum;
GraphType kind;
vector< vector >edges;
vector vexs;
public:
MGraph(GraphType t, T v[], int n, int e);
~MGraph() {};
T GetVexValue(int i);
int GetEdgeValue(int i, int j);
void prim();
void Kruskal(vector< EdgeType >&tree);
int xiabiao(T x)
{
for (int i = 0; i < vexnum; i++)
if (x == vexs[i])
return i;
return -1;
}
};
template
MGraph::MGraph(GraphType t, T v[], int n, int e)
{
vexnum = n;
edgenum = e;
kind = t;
vexs.resize(vexnum);
edges.resize(vexnum);
int i;
for (i = 0; i < n; i++)
{
vexs[i] = v[i];
}
for (i = 0; i < n; i++)
{
edges[i].resize(vexnum);
}
for (i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
edges[i][j] = 9999999;
}
}
EdgeType bian[10] = { {‘b’,‘d’,1},{‘a’,‘d’,2},{‘a’,‘b’,2},{‘d’,‘c’,3},{‘b’,‘c’,4},{‘a’,‘c’,5} }; //
for (i = 0; i < e; i++)
{
int va, vb, w;
va = xiabiao(bian[i].head);
vb = xiabiao(bian[i].tail);
w = bian[i].cost;
edges[va][vb] = edges[vb][va] = w;
}
}
template
T MGraph::GetVexValue(int i)
{
return vexs[i];
}
template
int MGraph::GetEdgeValue(int i, int j)
{
return edges[i][j];
}
template
void MGraph::prim()
{
Edge *miniedges = new Edge[vexnum];
int i;
for (i = 0; i < vexnum; i++)
{
miniedges[i].adjvex = GetVexValue(i);
miniedges[i].lowcost = GetEdgeValue(i, i);
}
miniedges[v].lowcost = 0;
for (i = 1; i < vexnum; i++)
{
int k, y;
for (y = 0; y < vexnum; y++)
{
if (miniedges[y].lowcost != 0)
{
k = y;
break;
}
}
for (y = 0; y < vexnum; y++)
{
if (miniedges[k].lowcost > miniedges[y].lowcost&&miniedges[y].lowcost != 0)
{
k = y;
}
}
cout << miniedges[k].adjvex << “–>” << GetVexValue(k) << “边的权值” << miniedges[k].lowcost << endl;
miniedges[k].lowcost = 0;
for (int j = 0; j < vexnum; j++)
{
if (GetEdgeValue(k, j) < miniedges[j].lowcost)
{
miniedges[j].adjvex = GetVexValue(k);
miniedges[j].lowcost = GetEdgeValue(k, j);
}
}
}
delete[]miniedges;
}
template
void MGraph::Kruskal(vector<EdgeType >&tree)
{
int *components = new int[vexnum];
int i;
for (i = 0; i < vexnum; i++)
{
components[i] = i;
}
int k = 0;
int j = 0;
while (k < vexnum - 1)
{
int h1 = xiabiao(tree[j].head);
int t1 = xiabiao(tree[j].tail);
int h2 = components[h1];
int t2 = components[t1];
if (h2 != t2)
{
cout << tree[j].head << “–>” << tree[j].tail << “权值” << tree[j].cost << endl;
k++;
for (i = 0; i < vexnum; i++)
{
if (components[i] == t2)
{
components[i] = h2;
}
}
}
j++;
}
delete[]components;
}
int main()
{
GraphType t = digraph;
char f[10] = { ‘a’,‘b’,‘c’,‘d’ };
int a = 4;
int b = 6;
MGraph MGraph(t, f, a, b);
MGraph.prim(0);
EdgeType r[10] = { {‘b’,‘d’,1},{‘a’,‘d’,2},{‘a’,‘b’,2},{‘d’,‘c’,3},{‘b’,‘c’,4},{‘a’,‘c’,5} };
vector<EdgeType > e;
int q;
for (q = 0; q < 6; q++)
{
e.push_back(r[q]);
}
MGraph.Kruskal(e);
return 0;
}
数据结构实验七
最新推荐文章于 2024-08-30 16:00:44 发布