SSL 3.02 模拟赛 T2 GF打Dota 【最短路】【次短路】

题目大意:

有一个无向图,求最短路和次短路

解题思路:

跑两次 S P F A SPFA ,第一次以 1 1 为起点,把 1 1 i i 的最短距离记录为 d i s i , 0 dis_{i,0}
第二次以 n n 为起点,把 n n i i 的最短距离记录为 d i s i , 1 dis_{i,1}

然后枚举每个点,尝试以其为中转站,记为点 i i ,枚举与 i i 相连的边,边的终点记录为 y y ,那么这样的路径长度就是 d i s i , 0 + dis_{i,0}+ 边权 + d i s y , 1 +dis_{y,1}

A c c e p t e d   c o d e Accepted\ code

#include<queue>
#include<cstdio>

using namespace std;

const int N = 10005;
const int M = 50005;
const int inf = 1e9;

struct Line {
	int to, w, next;
}e[M<<1];

int n, m, x, y, d, cnt, ans, answer, flag;
int dis[N][2], vis[N], last[N];

inline void add(int x, int y, int w) {
	e[++cnt].to = y; e[cnt].w = w; e[cnt].next = last[x]; last[x] = cnt;
}

void spfa(int S, int x) {
	for (int i = 0; i <= n; ++i) dis[i][x] = inf, vis[i] = 0;
	vis[S] = 1; dis[S][x] = 0;
    queue <int> q;
	q.push(S);
	while (q.size()) {
		int u = q.front(); q.pop(); vis[u] = 0;
		for (int i = last[u]; i; i = e[i].next) {
			int v = e[i].to, w = e[i].w;
			if (dis[v][x] > dis[u][x] + w) {
				dis[v][x] = dis[u][x] + w;
				if (!vis[v]) {
					vis[v] = 1;
					q.push(v);
				}
			}
		}
	}
}

int main() {
	scanf("%d %d", &n, &m);
	for (int x = 0, y = 0, w = 0, i = 1; i <= m; ++i) {
		scanf("%d %d %d", &x, &y, &w);
		add(x, y, w); add(y, x, w);
	}
	spfa(1, 0);
	spfa(n, 1);
	ans = inf;
	int p = 0;
	scanf("%d", &p);
	for (int i = 1; i <= n; ++i) {
		for (int j = last[i]; j; j = e[j].next) {
			int y = e[j].to, w = e[j].w;
			if (dis[i][0] + w + dis[y][1] > dis[n][0] && ans > dis[i][0] + w + dis[y][1])
				ans = dis[i][0] + w + dis[y][1];
		}
	}
	printf("%d", p == 1 ? ans : dis[n][0]);
}

猜你喜欢

转载自blog.csdn.net/qq_39798042/article/details/88077961