SPOJ——HIGHWAYS

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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,789评论 0 23
  • 有感 零星花几叶,最恼是秋声。 偏向离人落,萧萧满别情。
    巫小皇阅读 320评论 0 1
  • 一 十三年前,小男孩江小虾与小女孩善若水为同班同学,一起在“荷花县”读小学六年级。那时候的班主任老师名叫柳中庭,4...
    有狐在沔阅读 701评论 0 7
  • 你如星辰,只可仰望。 时间没能磨灭我的痴心与妄想, 只是不再明目张胆的狂热追逐。 你是我,深埋于心的信仰。
    生生1993阅读 192评论 0 0