HDU Today hdu 2112

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2112

文章末有一些相应的测试数据供参考。 

此题就是一个求最短路的问题,只不过现在的顶点名称变成了字符串而不是数字,我们用map做一个映射即可。

然后跑一个dijkstra算法就ok了,其中还用到了优先队列,每次取最小权值的边。

用时:1981 MS  还是挺快的

坑点

容器置空!!  map以及vector

此图是一个无向图!

可能有重边的情况!

首尾同名!

代码如下:

#include<iostream>
#include<vector>
#include<string>
#include<utility>
#include<map>
#include<queue>
#include<algorithm>
#include<functional>
using namespace std;
struct edge
{
    int to, cost;
};
const int INF = 0x3f3f3f3f, MAX = 155;
typedef pair<int, int> P;          //first为最短距离, second是顶点编号

vector<edge> G[MAX];
int d[MAX];                        //各个顶点的最短距离

void dijkstra(int s)
{
    priority_queue<P, vector<P>, greater<P> >que;
    fill(d, d + MAX, INF);
    d[s] = 0;
    que.push(P(0, s));

    while (!que.empty())
    {
        P p = que.top();
        que.pop();
        int v = p.second;
        if (d[v] < p.first)continue;
        for (int i = 0; i < G[v].size(); ++i)
        {
            edge e = G[v][i];
            if (d[e.to] > d[v] + e.cost)
            {
                d[e.to] = d[v] + e.cost;
                que.push(P(d[e.to], e.to));
            }
        }
    }
}

int main()
{
    int N;
    map<string, int> Map;
    while (cin >> N&&N != -1)
    {
        //!!记得置空!!
        Map.clear();
        for (int i = 0; i < MAX; ++i)G[i].clear();
        //少一个置空就过不了!!
        string start, s1, s2;
        cin >> start >> s2;
        Map[start] = 1;
        Map[s2] = 2;
        int item = 3;
        while (N--)
        {
            edge e;
            cin >> s1 >> s2 >> e.cost;
            if (!Map[s1])Map[s1] = item++;
            if (!Map[s2])Map[s2] = item++;
            e.to = Map[s2];
            G[Map[s1]].push_back(e);
            e.to = Map[s1];
            G[Map[s2]].push_back(e);
        }
        if (Map[start] == 2)
        {
            cout << 0 << endl;
            continue;
        }
        dijkstra(1);
        if (d[2] == INF)d[2] = -1;
        cout << d[2] << endl;
    }
}

测试数据

8
xiasha westlake
xiasha station 60
xiasha ShoppingCenterofHangZhou 30
station westlake 20
ShoppingCenterofHangZhou supermarket 10
station supermarket 10
xiasha supermarket 50
supermarket xiasha 20
supermarket westlake 40
0
xia  xia
-1

output

50
0

感谢您的阅读,祝您生活愉快~

原文地址:https://www.cnblogs.com/lv-anchoret/p/8364850.html