趣味算法-城市之间最短总距离
2011-12-29 22:30
267 查看
城市之间最短总距离:图为联通图。
(1) 图中所有顶点集合为V, 最小生成树顶点集合为U初始时V包含所有顶点,U为空。
(2) 从V中选取一个顶点V0,将其加入U。
(3) 从V0的邻接顶点中选取边权值最小的Vn,得到最小生成树的一条边,将Vn加入集合U。
(4) 再从V-U中再选取一个与V0, Vn邻接的顶点,找出权值最小的边。
(5) 重复上述步骤。
时间复杂度分析:与顶点的个数有关
n * ((1+2+ ... +n-1)*n) = n^2 * (n * (n-1)) / 2
空间复杂度 2*n 两个n个元素的数组保存集合U和V的数据。
可以用增大空间复杂的方式降低 时间复杂度,比如用二维数组保存边的权值,在循环时可降低时间复杂的
(1) 图中所有顶点集合为V, 最小生成树顶点集合为U初始时V包含所有顶点,U为空。
(2) 从V中选取一个顶点V0,将其加入U。
(3) 从V0的邻接顶点中选取边权值最小的Vn,得到最小生成树的一条边,将Vn加入集合U。
(4) 再从V-U中再选取一个与V0, Vn邻接的顶点,找出权值最小的边。
(5) 重复上述步骤。
#include <stdio.h> #define MAX_DIST 65535 int calc(int arrGraph[5][5], int nPoints) { int i = 0; int j = 0; int nDist = MAX_DIST; int nPoint = 0; int nResult = 0; int nLen = 0; // there are two sets for U and V, we will select point from U and set to V int *arrPointsU = (int*)malloc(nPoints*sizeof(int)); int *arrPointsV = (int*)malloc(nPoints*sizeof(int)); for (i = 0; i < nPoints; i++) { arrPointsU[i] = i; arrPointsV[i] = -1; } // start from point 0 arrPointsV[0] = 0; arrPointsU[0] = -1; int nLenV = 1; while (nLenV < nPoints) { nDist = MAX_DIST; i = 0; while(i < nLenV) { for (j = 0; j < nPoints; j++) { if (arrPointsU[j] == -1) continue; nLen = arrGraph[arrPointsV[i]][arrPointsU[j]]; if ((nLen > 0) && (nLen < nDist)) { nPoint = j; nDist = nLen; } } i++; } if (nDist != MAX_DIST) { nLenV++; arrPointsV[i] = nPoint; arrPointsU[nPoint] = -1; nResult += nDist; printf("Point=%d\n", nPoint); } } printf("Distance = %d \n", nResult); free(arrPointsV); free(arrPointsU); return nResult; } int main() { int nDist = 0; int i =0; int arrTest[5][5]= { 0, 2, 5, 0, 3, 2, 0, 0, 4, 0, 5, 0, 0, 0, 5, 0, 4, 0, 0, 2, 3, 0, 5, 2, 0, }; nDist = calc(arrTest, 5); printf("shortest distance=%d\n", nDist); scanf("%d", &i); return 0; }
时间复杂度分析:与顶点的个数有关
n * ((1+2+ ... +n-1)*n) = n^2 * (n * (n-1)) / 2
空间复杂度 2*n 两个n个元素的数组保存集合U和V的数据。
可以用增大空间复杂的方式降低 时间复杂度,比如用二维数组保存边的权值,在循环时可降低时间复杂的
相关文章推荐
- 趣味算法-城市之间最短路径
- 城市之间的最短总距离(最小生成树算法)
- 用于评估实体之间距离的聚会算法
- 百度地图API:计算任意两个城市之间的距离
- java通过经纬度计算两个点的之间的距离的算法 (单位:米)
- c/c++常用算法(15) -- 经典数据结构(城市之间的最短距离问题)
- 游戏开发中的数学和物理算法(3):点之间的距离
- 微软算法100题11 求二叉树中两节点之间的最大距离
- 最小生成树(城市之间的最短距离)
- 求城市里两点之间的最短距离.
- PAT程序设计练习——甲级1003(任意两个城市最短距离、Floyd最短路径算法)
- Javascript 地图经度纬度之间的距离的算法(轉)
- [python]My Unique JsonDiff算法——如何计算2个json串之间的差距并Diff出来(一):编辑距离(Levenshtein)算法
- 计算两个经纬度之间的距离(python算法)
- 算法竞赛入门经典: 第四章 函数与递归 4.1求两点之间距离
- java通过经纬度计算两个点的之间的距离的算法
- [Game] 游戏开发中的数学和物理算法:点之间的距离
- 游戏开发中的数学和物理算法(3):点之间的距离
- 武汉科技大学ACM :1006: 零起点学算法25——求两点之间的距离
- GJK算法求凸多边形之间的距离