Dijkstra + priority_queue


模版

EOJ 最短路:http://acm.cs.ecnu.edu.cn/problem.php?problemid=1817

#include <cstdio>
#include <deque>
#include <set>
#include <string>
#include <map>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
typedef long long LL;

#define Debug(x) (cerr << #x << " = " << (x) << endl)
#define Debug2(x, y) (cerr << #x << " = " << (x) << ", " << #y << " = " << (y) << endl)
template<class T> inline T& RD(T &x){  
    char c; for (c = getchar(); c < '0'; c = getchar()); x = c - '0'; for (c = getchar(); '0' <= c && c <= '9'; c = getchar()) x = x * 10 + c - '0';  
    return x;  
}


const int inf = 0x3f3f3f3f;
const int maxn = 1001;


//vector<int> g[maxn];
int g[maxn][maxn];
bool used[maxn];
int dist[maxn];
priority_queue<pair<int,int>, vector<pair<int,int> > ,greater<pair<int,int> > > q;
int Dijkstra(int s,int e){
	
	memset(used,false,sizeof(used));
	memset(dist,0x3f,sizeof(dist));
	while(!q.empty())q.pop();

	dist[s] = 0;
	q.push(make_pair(0,s));

	while(!q.empty()){	
		int u = q.top().second;
		int tt = q.top().first;
		
		if(u == e){
			return tt;
		}
		q.pop();
		if(used[u] == false){

			used[u] = true;
			for(int v=1;v<=e;v++){
				if(!used[v] && dist[u]+g[u][v] < dist[v]){
					dist[v] = dist[u] + g[u][v];
					q.push(make_pair(dist[v],v));
				}
			}
		}
	}
	return dist[e];
}



int main(){
	//Dijkstra(1);
	int n,m;
	while(~scanf("%d%d",&n,&m)){

		memset(g,0x3f,sizeof(g));

		for(int i=0;i<m;i++){
			int a,b,c;
			scanf("%d%d%d",&a,&b,&c);
			g[a][b] = c;
		}
		
		int ans = Dijkstra(1,n);
		if(ans >= inf)ans = -1;
		printf("%d\n", ans);
	}	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值