跳到正文

题解

GESP7级 202512 -1

bbzxy1122约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月31日
更新
2025年12月31日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1

关于 SPFA…它又活了!

分享一个比较暴力的写法:

把每个点到其他点都SPFA一边,算出最短路,在统计就行了,理论时间复杂度是 O(N2MN^2M),但由于是个稀疏图,就奇迹般地过了

具体方法:

用dis[i][j] 存点i到j的距离,特别的dis[i][i]=0 后面优化为一维了

用邻接表存边,这里用vector

对于每个点都SPFA一遍

最后统计每个点到其他点的最长距离再比较就行了

可以看看其他大佬有更优秀的写法

Code:

C++
#include<bits/stdc++.h>
using namespace std;
const int N = 2005;
int n, m, dis[N], vis[N], ans, maxs;
vector<int> a[N];
queue<int> q;

//SPFA大人
void spfa(int k) {
	q.push(k);
	while (!q.empty()) {
		int x = q.front();
		vis[x] = 0;
		q.pop();
		for (int i = 0; i < a[x].size(); i++) {
			int to = a[x][i];
			if (dis[to] > dis[x] + 1) {
				dis[to] = dis[x] + 1;
				if (!vis[to]) {
					vis[to] = 1;
					q.push(to);
				}
			}
		}
	}
}

int main() {
	cin >> n >> m;

	//存边
	for (int i = 1; i <= m; i++) {
		int x, y;
		cin >> x >> y;
		a[x].push_back(y);
		a[y].push_back(x);
	}

	maxs = INT_MAX;
	for (int i = 1; i <= n; i++) {
		//别忘了初始化
		while (!q.empty()) q.pop();
		for (int j = 1; j <= n; j++) {
			vis[j] = 0;
			dis[j] = 1e9;//每个点刚开始到其他点是无穷大的
			if (i == j) dis[j] = 0;
		}

		//SPFA
		spfa(i);

		//比较
		int g = -1;
		for (int j = 1; j <= n; j++) {
			g = max(g, dis[j]);
		}
		if (g < maxs) {
			maxs = g;
			ans = i;
		}
	}

	cout << ans;
	return 0;
}

完结撒花

希望不要被HACK

原文