1128. 信使 单源最短路 dijkstra Floyd

d:

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
const int N = 110;
int g[N][N];
int dist[N];
int n,m;
bool st[N];
int dijkstra()
{
    memset(dist,0x3f,sizeof dist);
    dist[1] = 0;

    for(int i = 1; i < n; i ++)
    {
        int t = 0;
        for(int j = 1; j <= n; j ++)    //找出未被标记中最小的点
        {
            if(!st[j] && (t == 0 || dist[t] > dist[j]))
                t = j;
        }
        st[t] = true;                   //标记已使用
        //cout << t << " "; //printf调试法
        for(int k = 1; k <= n; k ++)    //用最小的点,更新其他点
            dist[k] = min(dist[k],dist[t] + g[t][k]);
    }
    int res = -1;
    for(int i = 1; i <= n; i ++)
    {
        if(dist[i] == 0x3f3f3f3f) return -1;
        res = max(res,dist[i]);
    }
    return res;
}
int main()
{
    cin >> n >> m;
    memset(g,0x3f3f3f3f,sizeof g);
    for(int i = 1; i <= m; i ++)
    {
        int a,b,c;
        cin >> a >> b >> c;
        if(a == b) continue;
        g[a][b] = min(g[a][b],c);
        g[b][a] = min(g[b][a],c);
    }
    cout <<  dijkstra() << endl;

    return 0;
}

f:

#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 110, INF = 0x3f3f3f3f;

int n, m;
int d[N][N];

int main()
{
    cin >> n >> m;

    memset(d, 0x3f, sizeof d);
    for (int i = 1; i <= n; i ++ ) d[i][i] = 0;
    for (int i = 0; i < m; i ++ )
    {
        int a, b, c;
        cin >> a >> b >> c;
        d[a][b] = d[b][a] = min(d[a][b], c);
    }

    for (int k = 1; k <= n; k ++ )
        for (int i = 1; i <= n; i ++ )
            for (int j = 1; j <= n; j ++ )
                d[i][j] = min(d[i][j], d[i][k] + d[k][j]);

    int res = 0;
    for (int i = 1; i <= n; i ++ )
        if (d[1][i] == INF)
        {
            res = -1;
            break;
        }
        else res = max(res, d[1][i]);

    cout << res << endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值