解题报告:虽然没有负环,不过用spfa效率也不错。

Code

#include <stdio.h>
#include <iostream>
#include <queue>
#include <algorithm>
#include <string.h>
using namespace std;
const int maxn = (int)1e5+5;
const int inf = 0x3f3f3f3f;

struct Node{
	int to;
	int w;
	Node(int to, int w) {
		this->to = to;
		this->w = w;
	}
};
vector<Node> tab[maxn];
bool vis[maxn]; //是否在队列中 
int cnt[maxn];  //入队的次数 
int dist[maxn]; //distance

void init(int n, int m) {
	for (int i = 0; i < n; i++) {
		tab[i].clear();
	}
	
	int v,u,w;
	for (int i = 0; i < m; i++) {
		scanf("%d%d%d",&u,&v,&w);
		tab[u].push_back(Node(v, w));
		tab[v].push_back(Node(u, w));
	}
}

queue<int> Q;
void spfa(int from) {
	memset(vis, false, sizeof(vis));
	memset(cnt, 0, sizeof(cnt));
	memset(dist, inf, sizeof(dist));
	while (!Q.empty()) {
		Q.pop();
	}
	Q.push(from);
	vis[from] = true;
	dist[from] = 0;
	cnt[from]++;
	while (!Q.empty()) {
		int x = Q.front();
		Q.pop();
		vis[x] = false;
		for (int i = 0; i < tab[x].size(); i++) {
			if (dist[tab[x][i].to] > dist[x] + tab[x][i].w) {
				dist[tab[x][i].to] = dist[x] + tab[x][i].w;
				if (!vis[tab[x][i].to]) {
					cnt[tab[x][i].to]++;
					vis[tab[x][i].to] = true;
					Q.push(tab[x][i].to);
				}
			}
		}
	}
}

int main() {
	int n, m, start, end;
	while (scanf("%d%d", &n, &m) != EOF) {
		init(n, m);
		scanf("%d%d", &start, &end);
		spfa(start);
		printf("%d\n", dist[end] == inf ? -1 : dist[end]);
	}
	return 0;
}