HDOJ 2112 HDU Today

本文详细介绍了如何解决公交网络中两点之间的最短路径问题,通过构建图并使用Floyd算法或SPFA算法实现路径查找。注意点包括处理无向图及多路径情况,确保保存最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给出一张公交网络,求两点之间的最短路径

链接:http://acm.hdu.edu.cn/showproblem.php?pid=2112

思路:建图,floyd或者SPFA随便搞搞就过了。

注意点:无向图,并且可能存在两点之间存在多条路径,保存最短的那条即可。


以下为AC代码:

Run IDSubmit TimeJudge StatusPro.IDExe.TimeExe.MemoryCode Len.LanguageAuthor
119177282014-10-19 23:37:08Accepted21121953MS1376K1997 BG++luminous11

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <deque>
#include <list>
#include <cctype>
#include <algorithm>
#include <climits>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#define INF 0x3f3f3f3f
using namespace std;

int adj[505][505];
void floyd ( int n )
{
    for ( int i = 0; i < n; i ++ )
    {
        for ( int j = 0; j < n; j ++ )
        {
            for ( int k = 0; k < n; k ++ )
            {
                adj[j][k] = min ( adj[j][i] +adj[i][k], adj[j][k] );
            }
        }
    }
    for ( int i = 0; i < n; i ++ )
    {
        adj[i][i] = 0;
    }
}

int main()
{
    map<string,int> p;
    string be_s, en_s;
    string str_1, str_2;
    int len;
    int n;
    ios::sync_with_stdio( false );
    while ( cin >> n )
    {
        p.clear();
        memset ( adj, 0x3f3f3f3f, sizeof ( adj ) );
        if ( n == -1 )
        {
            break;
        }
        int cnt = 0;
        cin >> be_s >> en_s;
        if ( ! p[be_s] )
        {
            p[be_s] = cnt ++;
        }
        if ( ! p[en_s] )
        {
            p[en_s] = cnt ++;
        }
        int a, b;
        for ( int i = 0; i < n; i ++ )
        {
            cin >> str_1 >> str_2;
            cin >> len;
            if ( ! p[str_1] )
            {
                p[str_1] = cnt ++;
            }
            if ( ! p[str_2] )
            {
                p[str_2] = cnt ++;
            } 
            if ( adj[p[str_1]][p[str_2]] > len )
                adj[p[str_1]][p[str_2]] = adj[p[str_2]][p[str_1]] = len;
        }
        floyd ( cnt );
        if ( adj[p[be_s]][p[en_s]] != INF )
        {
            cout << adj[p[be_s]][p[en_s]] << endl;
        }
        else
        {
            cout << "-1" << endl;
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值