CodeForces - 20C Dijkstra?

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

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

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

#include
#include
#include
#include
#include
#include
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) {};
};

vectorG[N];
queueque;

void SPFA(int s) {
	for(int i=0; idis[n-1]) continue;
		for(int j=0; jdis[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;
	stackstk;
	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;
}

 

你可能感兴趣的:(最短路)