凡人修c传(二十)最短路K - Candies(dijkstra堆优化+差分约束)

传送门:SDUT 2017春夏个人专题训练四 最短路练习 - Virtual Judge

        什么叫差分约束?差分约束系统——百度百科

看题解大部分用的是spfa算法,但spfa用的是栈,如果用队列实现会t,我也不知道为啥。听学长说,spfa这个算法,他死了。除非像判环这种万不得已才用,其余的时候最好不要用。所以,我用了dijkstra堆优化来解决,这样也不用考虑是用栈还是用队列的问题了。

代码如下:

#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<math.h>
#include<string.h>
#include<stack>
#include<queue>
#include<vector>
typedef long long ll;
using namespace std;
int n,m;
int h[300000];
int ne[300000];
int e[300000];
int w[300000];
int idx;
int dist[300000];
void add(int a,int b,int c){
	e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
bool c[300000];
void dj(int x){
	for(int i=1;i<=n;i++){
		c[i]=0;
		dist[i]=0x3f3f3f3f;
	}
	dist[x]=0;
	priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>q;
	pair<int,int>now;
	now.first=0;
	now.second=x;
	q.push(now);
	while(!q.empty()){
		pair<int,int>t=q.top();
		q.pop();
		int ver=t.second;
		if(c[ver])continue;
		c[ver]=1;
		for(int i=h[ver];i!=-1;i=ne[i]){
			int j=e[i];
			if(dist[j]>dist[ver]+w[i]){
				dist[j]=dist[ver]+w[i];
				now.first=dist[j];
				now.second=j;
				q.push(now);
			}
		}
	}
	
}
int main()
{
//	ios::sync_with_stdio(false);
//	cin.tie();
//	cout.tie();
	memset(h,-1,sizeof h);
	scanf("%d%d",&n,&m);
	idx=1;
	for(int i=1;i<=m;i++){
		int l,r,ww;
		scanf("%d%d%d",&l,&r,&ww);
		add(l,r,ww); 
	}
	dj(1);
//	int k=dist[n];
//	if(dist[n]>=0x3f3f3f3f)dist[n]=0;
//	dj(n);
//	if(dist[1]>=0x3f3f3f3f)dist[1]=0;
//	k=max(k,dist[1]);
	cout<<dist[n];

	return 0; 
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值