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(n2)怠堪,一開始幾發(fā)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;
}