美文网首页
SPOJ——HIGHWAYS

SPOJ——HIGHWAYS

作者: xz闲语岁月 | 来源:发表于2017-08-02 21:54 被阅读0次

    Problem

    A number of cities are connected by a network of highways. Each highway is bidirectional and connects two cities, with a given travel time. What is the shortest time to get from a given city to another given city?

    Input

    The first line of input contains the number of test cases.
    Each test case starts with a line containing the number of cities n (2 ≤ n ≤ 100000), the number of highways m (1 ≤ m ≤ 100000), the starting city and the ending city. Cities are numbered from 1 to n.
    Then m lines follow, each describing one highway. The description consists of the two distinct city numbers and the time in minutes to travel along the highway. The time will be between 1 and 1000.

    Output

    For each test case output a single line containing the minimum time it takes to get from the start to the destination. If no connection exists, output NONE.

    Sample Input

    2
    4 2 1 4
    1 2 5
    3 4 5
    4 4 1 4
    1 2 5
    2 3 5
    3 4 5
    4 2 6

    Sample Output

    NONE
    11


    思路

    最短路模板题,dijkstra+priority_queue即可。不过注意使用priority_queue的时候加上greater参数,否则小根堆变大根堆,复杂度直接退化为O(n²),一开始几发TLE就是这个问题。

    代码

    #include<iostream>
    #include<algorithm>
    #include<cstring>
    #include<queue>
    #include<vector>
    #include<functional>
    #define N 100005
    using namespace std;
    typedef pair<int, int> P;
    struct edge {
        int to, cost;
        edge(int t, int c) :to(t), cost(c) {};
    };
    int V,E,start,endd;
    vector<edge>G[N];
    int d[N];
    void dijkstra(int s) {
        priority_queue<P, vector<P>,greater<P>>q;
        memset(d, 0x3f, sizeof(d));
        d[s] = 0;
        q.push(P(0, s));
        while (!q.empty()) {
            P p = q.top(); q.pop();
            int v = p.second;
            if (d[v] < p.first)continue;
            for (size_t 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;
                    q.push(P(d[e.to], e.to));
                }
            }
        }
    }
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(0);
        int t;
        cin >> t;
        while (t--) {
            for (int i = 0; i < N; i++)G[i].clear();
            int v1, v2, w;
            cin >> V >> E >> start >> endd;
            for (int i = 0; i < E; i++) {
                cin >> v1 >> v2 >> w;
                G[v1].push_back(edge(v2, w));
                G[v2].push_back(edge(v1, w));
            }
            dijkstra(start);
            if (d[endd] > 1000000)cout << "NONE" << endl;
            else cout << d[endd] << endl;
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:SPOJ——HIGHWAYS

          本文链接:https://www.haomeiwen.com/subject/wdoylxtx.html