关于 SPFA…它又活了!
分享一个比较暴力的写法:
把每个点到其他点都SPFA一边,算出最短路,在统计就行了,理论时间复杂度是 O(),但由于是个稀疏图,就奇迹般地过了
具体方法:
用dis[i][j] 存点i到j的距离,特别的dis[i][i]=0 后面优化为一维了
用邻接表存边,这里用vector
对于每个点都SPFA一遍
最后统计每个点到其他点的最长距离再比较就行了
可以看看其他大佬有更优秀的写法
Code:
#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