- dijkstra 算法,利用优先队列优化,找到最近的点。
- 添加vis数组剪枝。
- 优先队列重载运算符时,右边的值优先级大放在前,所以 a > b表示从小到大排列。
题目链接:http://acm.hust.edu.cn/vjudge/problem/17126
#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<ctime>
#include<vector>
#include<fstream>
#include<list>
using namespace std;
#define ms(s) memset(s,0,sizeof(s))
typedef unsigned long long ULL;
typedef long long LL;
const double PI = 3.141592653589;
const int INF = 0x3fffffff;
struct Edge{
int to, cost;
Edge(int nto, int ncost) : to(nto),cost(ncost){}
Edge(){};
bool operator < (const Edge& rhs) const{
return cost > rhs.cost;
}
};
vector<vector<Edge> > G;
priority_queue<Edge> pq;
int d[30010], n;
int dijkstra(int head, int tail){
while(!pq.empty())
pq.pop();
fill(d+1, d+n+1, INF);
pq.push(Edge(head, 0));
d[head] = 0;
Edge t;
while(!pq.empty()){
t = pq.top(); pq.pop();
if(t.to == tail)
break;
if(d[t.to] < t.cost)
continue;
for(int i = 0; i < G[t.to].size(); ++i){
Edge e = G[t.to][i];
if(d[e.to] > t.cost + e.cost) {
d[e.to] = t.cost + e.cost;
pq.push(Edge(e.to, d[e.to]));
}
}
}
return t.cost;
}
int main(){
// freopen("/Users/really/Documents/code/input","r",stdin);
// freopen("/home/really/Document/output","w",stdout);
// ios::sync_with_stdio(false);
int a,b,c, m;
scanf("%d%d",&n,&m);
G.resize(n+5);
for(int i = 0; i < m; ++i){
scanf("%d%d%d", &a, &b, &c);
G[a].push_back(Edge(b,c));
}
int ans = dijkstra(1,n);
printf("%d\n",ans);
return 0;
}