旧代码 - 最短路 Spfa

/*
PROG:   spfa
ID  :   ouyangyewei
LANG:   C++
*/
#include <queue>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define onlinejudge

const int maxn = 1004;
const int INF = 0x3F3F3F3F;

bool inq[maxn];
int  N, M, destination;
int  dist[maxn], path[maxn], edge[maxn][maxn];

void spfa(int src)
{
    int i, u;
    queue <int> q;
    
    dist[src]=0, inq[src]=true;
    q.push(src);
    while (!q.empty())
    {
        u = q.front();
        q.pop();
        inq[u] = false;
        
        for (i=0; i<N; ++i)
        {
            if (dist[u]+edge[u][i] < dist[i])
            {
                path[i] = u;
                dist[i] = dist[u]+edge[u][i];
                if (!inq[i])
                    q.push(i), inq[i]=true;
            }
        }// end of for
    }// end of while
}// spfa

void dfs(int src, int xx)
{
    if (xx != src)
        dfs(src, path[xx]);
    
    if (xx != destination)
        printf("%d-->", xx);
    
    return ;
}// dfs

int main()
{
#ifdef onlinejudge
    freopen("E:\\bellman.txt", "r", stdin);
    freopen("E:\\bellman_ans.txt", "w", stdout);
#endif

    int i, j, a, b, c;
    while (~scanf("%d %d", &N, &M), N+M!=0)
    {
        memset(dist, INF, sizeof(dist));
        memset(inq, false, sizeof(inq));
        memset(edge, INF, sizeof(edge));
        for (i=0; i<M; ++i)
        {
            scanf("%d %d %d", &a, &b, &c);
            edge[a][b] = c;
        }// end of for
        
        spfa( 0 );
        for (i=1; i<N; ++i)
        {
            printf("%d     ", dist[i]);
            destination = i;
            dfs(0, destination);
            printf("%d\n", i);
        }// end of for
    }// end of while
    
    return 0;
}
/*
Test:
    
7 10
0 1 6
0 2 5
0 3 5
1 4 -1
2 1 -2
2 4 1
3 2 -2
3 5 -1
4 6 3
5 6 3

0 0

Result:
  
1     0-->3-->2-->1
3     0-->3-->2
5     0-->3
0     0-->3-->2-->1-->4
4     0-->3-->5
3     0-->3-->2-->1-->4-->6  
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值