CodeForces - 20C Dijkstra?

 用SPFA T了好几发,最后加上一句

if(dis[a]>dis[n-1]) continue;

就过了,还有就是记得开long long

#include<queue>
#include<stack>
#include<cstring>
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;

const int N=200000+100;
const ll INF=0x3f3f3f3f3f3f3f3f;
int n,m;
ll dis[N];
bool vis[N];
int parent[N];


struct edge {
	int from,to,dist;
	edge(int a,int b,int c):from(a),to(b),dist(c) {};
};

vector<edge>G[N];
queue<int>que;

void SPFA(int s) {
	for(int i=0; i<n; i++) dis[i]=INF,parent[i]=-1;
	dis[s]=0;
	que.push(s);
	while(!que.empty()) {
		int a=que.front();
		que.pop();

		vis[a]=0;
		if(dis[a]>dis[n-1]) continue;
		for(int j=0; j<G[a].size(); j++) {
			edge E=G[a][j];
			if(dis[E.to]>dis[E.from]+E.dist) {
				dis[E.to]=dis[E.from]+E.dist;
				parent[E.to]=E.from;
				if(!vis[E.to]) {
					vis[E.to]=1;
					que.push(E.to);
				}
			}
		}
	}
}

void print() {
	int s=n-1;
	stack<int>stk;
	stk.push(n-1+1);
	while(parent[s]!=-1) {
		stk.push(parent[s]+1);
		s=parent[s];
	}
	if(s!=0) {
		printf("-1\n");
		return ;
	}
	while(!stk.empty()) {
		printf("%d ",stk.top());
		stk.pop();
	}
}

int main() {
	cin>>n>>m;
	while(m--) {
		int from,to,dist;
		cin>>from>>to>>dist;
		G[from-1].push_back(edge(from-1,to-1,dist));
		G[to-1].push_back(edge(to-1,from-1,dist));
	}
	SPFA(0);
//	printf("%d\n",dis[0]);
	print();
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值