hdu 2544 最短路(bellman算法和floyd算法)(c++)

hdu 2544 最短路(bellman算法和Floyd算法)(c++)

题目链接:hdu 2544 最短路
题目描述: 在每年的校赛里,所有进入决赛的同学都会获得一件很漂亮的t-shirt。但是每当我们的工作人员把上百件的衣服从商店运回到赛场的时候,却是非常累的!所以现在他们想要寻找最短的从商店到赛场的路线,你可以帮助他们吗?
Input: 输入包括多组数据。每组数据第一行是两个整数N、M(N<=100,M<=10000),N表示成都的大街上有几个路口,标号为1的路口是商店所在地,标号为N的路口是赛场所在地,M则表示在成都有几条路。N=M=0表示输入结束。接下来M行,每行包括3个整数A,B,C(1<=A,B<=N,1<=C<=1000),表示在路口A与路口B之间有一条路,我们的工作人员需要C分钟的时间走过这条路。
输入保证至少存在1条商店到赛场的路线。
Outout: 对于每组输入,输出一行,表示工作人员从商店走到赛场的最短时间
样例输入:

2 1
1 2 3
3 3
1 2 5
2 3 5
3 1 2
0 0

样例输出:

3
2

bellman算法:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define INF 0x3f3f3f3f
int m,n;
int a,b,c;
int cnt;
int d[105];
struct node{
    int x,y,v;
};
node graph[20005];
void bellman()
{
    d[1] = 0;
    for(int k = 1; k <= n; k++){
        for(int i = 0; i < cnt; i++){
              int u = graph[i].x;
              int v = graph[i].y;
              if(d[u] > d[v] + graph[i].v){
                    d[u] = d[v] + graph[i].v;
              }
        }
    }
    cout << d[n] << endl;
}
int main()
{
    while(1){
        memset(d,0x3f,sizeof(d));
        cnt = 0;
        cin >> n >>m;
        if(n == 0 && m == 0){
            break;
        }
        while(m--){
            cin >> a >> b >> c;
            graph[cnt].x = a; graph[cnt].y = b; graph[cnt++].v = c;
            graph[cnt].x = b; graph[cnt].y = a; graph[cnt++].v = c;
        }
        bellman();
    }
    return 0;
}

Floyd算法:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define INF 0x3f3f3f3f
int graph[105][105];
int n,m;
int floyd(){
    for(int k = 1;k <= n;k++){
        for(int i = 1; i <= n; i++){
            if(graph[i][k] != INF){
                for(int j = 1; j <= n; j++){
                    if(graph[i][j] > graph[i][k] + graph[j][k]){
                        graph[i][j] = graph[i][k] + graph[j][k];
                    }
                }
            }
        }
    }
    return graph[1][n];
}
int main()
{
    int a,b,c;
    while(1){
        memset(graph, 0x3f, sizeof(graph));
        cin >> n >> m;
        if(n == 0 && m == 0){
            break;
        }
        else{
            while(m--){
                cin >> a >> b >> c;
                graph[a][b] = graph[b][a] = c;
            }
        }
        cout << floyd() << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值