intGraph::prim(){ for (int i = 1; i <= num_v; i++) VexList[i].flag = false;
int sum = 0; int min_w; int* visited = newint[num_v]; int index = 0;
for (int i = 1; i <= num_v; i++) { if (VexList[i].firstAdj) { visited[index++] = i; VexList[i].flag = true; break; } }
while (index < num_v) { for (int i = 0; i < index; i++) { EdgeNode* p = VexList[visited[i]].firstAdj; while (VexList[p->vertex].flag && p->next) { p = p->next; } if (VexList[p->vertex].flag) continue; else { min_w = p->weight; visited[index] = p->vertex; break; } }
for (int i = 0; i < index; i++) { EdgeNode* p = VexList[visited[i]].firstAdj; while (p) { if (p->weight <= min_w && !VexList[p->vertex].flag) { min_w = p->weight; visited[index] = p->vertex; } if (!p->next) break; p = p->next; } }
VexList[visited[index]].flag = true; index++; sum += min_w; }
int sum = 0; EdgeNode* edges = new EdgeNode[num_e]; int index = 0; int begin, end; int* set = newint[num_v + 1]; for (int i = 1; i <= num_v; i++) set[i] = i;
2. Storing
从第一个顶点开始,将所有边存入edges数组中。
为避免将同一条边“双向”存储,只存储从小顶点到大顶点方向的边,故在4行进行了判断。
注意存储时还要包括边的“起点”,这是与以往不同的地方,以便于后续对连通分支的判断。
1 2 3 4 5 6 7 8 9 10 11 12
for (int i = 1; i <= num_v; i++) { EdgeNode* p = VexList[i].firstAdj; while (p) { if (p->vertex > i) { edges[index].vAdj = i; edges[index].vertex = p->vertex; edges[index].weight = p->weight; index++; } p = p->next; } }
3. Sorting
将存储的边按权从小到大进行排序,采用冒泡算法。
1 2 3 4 5 6 7 8 9
for (int i = 0; i < num_e; i++) { for (int j = i + 1; j < num_e; j++) { if (edges[i].weight > edges[j].weight) { EdgeNode temp = edges[i]; edges[i] = edges[j]; edges[j] = temp; } } }
for (int i = 0, j = 0; i < num_e && j < num_v; i++) { if (set[edges[i].vAdj] != set[edges[i].vertex]) { sum += edges[i].weight; begin = set[edges[i].vAdj]; end = set[edges[i].vertex]; for (int k = 1; k <= num_v; k++) { if (set[k] == end) set[k] = begin; } j++; } }
intGraph::kruskal(){ int* set = newint[num_v + 1]; int sum = 0; EdgeNode* edges = new EdgeNode[num_e]; int index = 0; int begin, end; for (int i = 1; i <= num_v; i++) set[i] = i;
for (int i = 1; i <= num_v; i++) { EdgeNode* p = VexList[i].firstAdj;
while (p) { if (p->vertex > i) { edges[index].vAdj = i; edges[index].vertex = p->vertex; edges[index].weight = p->weight; index++; } p = p->next; } }
for (int i = 0; i < num_e; i++) { for (int j = i + 1; j < num_e; j++) { if (edges[i].weight > edges[j].weight) { EdgeNode temp = edges[i]; edges[i] = edges[j]; edges[j] = temp; } } }
for (int i = 0, j = 0; i < num_e && j < num_v; i++) { if (set[edges[i].vAdj] != set[edges[i].vertex]) { sum += edges[i].weight; begin = set[edges[i].vAdj]; end = set[edges[i].vertex]; for (int k = 1; k <= num_v; k++) { if (set[k] == end) set[k] = begin; } j++; } }
delete[] set; delete[] edges; return sum; }
0x06 析构函数
逐个结点释放内存。
1 2 3 4 5 6 7 8 9 10
Graph::~Graph(){ for (int i = 1; i <= num_v; i++) { while (VexList[i].firstAdj) { EdgeNode* temp = VexList[i].firstAdj; VexList[i].firstAdj = temp->next; delete temp; } } delete[] VexList; }