趣味算法-城市之间最短总距离

来源:互联网 发布:ib课程网络教学 编辑:程序博客网 时间:2024/04/30 04:36

城市之间最短总距离:图为联通图。


(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 65535int 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的数据。

可以用增大空间复杂的方式降低 时间复杂度,比如用二维数组保存边的权值,在循环时可降低时间复杂的