求每对顶点间的最短路径

  用动态规划的方法,解决有些爱那个图G=(V,E)上每对顶点间的最短路径问题。路径图用邻接矩阵存储。具体的描述参考:http://tayoto.blog.hexun.com/26047245_d.html里面的第一点的介绍。

直接上代码:

/*************************************************************************
    > File Name: show_all_pairs_shortest_path.cpp
    > Author: He Xingjie
    > Mail: gxmshxj@163.com
    > Created Time: 2014年06月10日 星期二 17时32分37秒
    > Description: 
 ************************************************************************/
#include<iostream>
#include<cstdio>
#include<stack>

using namespace std;

#define MAX 50
#define INF 65535

int map[MAX][MAX], dist[MAX], path[MAX][MAX];

void ExtendShortestPaths(int n)
{
    int i, j, k;

    for (i=0; i<n; i++)
        for (j=0; j<n;j++)
            for (k=0; k<n; k++)
                if (map[i][j] > map[i][k] + map[k][j])
                {
                    map[i][j] = map[i][k] + map[k][j];
                    path[i][j] = path[k][j];
                }
}

void ShowAllPairsShortestPaths(int n)
{
    int i;

    for (i=1; i<n-1; i++)
        ExtendShortestPaths(n);
}

void PrintMap(int n)
{    
    printf("Map:\n");
    for (int i=0; i<n; i++)
    {
        for (int j=0; j<n; j++)
            cout<<map[i][j]<<"  ";
        cout<<endl;
    }
}

void PrintShortestPaths(int n)
{
    int i, j;
    stack<int> st;

    printf("Shortest Path:\n");
    for (i=0; i<n; i++)
        for (j=0; j<n; j++)
        {
            st.push(j+1);
            int pre = path[i][j];
            while (pre != i+1 && pre != 0)
            {
                /*
                 *st.push(path[i][pre-1]);
                 *pre = path[i][pre-1];
                 */
                st.push(pre);
                pre = path[i][pre-1];
                
            }
            printf("%d: %d", map[i][j], i+1);

            while (!st.empty())
            {
                printf("->%d",st.top());
                st.pop();
            }
            printf("\n");
        }
}

int main()
{
    int n;

    freopen("input.txt", "r", stdin);

    cin>>n;
    for (int i=0; i<n; i++)
        for(int j=0; j<n; j++)
        {
            cin>>map[i][j];
            if (map[i][j] != INF)
                path[i][j] = i+1;
            else
                path[i][j] = 0;
        }

    ShowAllPairsShortestPaths(n);
    
    PrintMap(n);

    PrintShortestPaths(n);

    return 0;
}

2014/6/10 22:16

 

输入数据:

5
0 3 8 65535 -4
65535 0 65535 1 7
65535 4 0 65535 65535
2 65535 -5 0 65535
65535 65535 65535 6 0

//最大值设置为65535

输出结果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值