题意,求最短路的最大值
这题理解题意后第一个想到的就是Floyd,超时
看了题解后并与g佬讨论,现整理如下:
这道题由于图中的每一条边长度都为1 , 所以不会出现有两条边之和小于另一条边的情况,所以应该用BFS,即搜到某一情况时,该边的长度就已经是最小值了,(搜索第一层就是长度为1的,第二层就是长度为2的....),所以元素只入队一次,再在每个点BFS一遍,当然BFS后有距离是INF的就可以break了,直接输出-1,此时复杂度为O(n*n)。
但是这道题网上有SPFA过的,原论文中证明的复杂度是每个元素最多入队n-1次,每个点都要入队,每个点都要SPFA一遍,所以理论上这样复杂度为O(n*n*n),开始我以为这样甚至比Floyd还要慢,但事实上,spfa在实际操作中一般(注意是一般,不是一定)元素入队在两到三次,所以SPFA复杂度接近O(n),emmmm....如果错了还望指正,
至少在这道题中,SPFA入队不超过两次,所以SPFA碰巧通过了,而dij多了一个log就被卡了。
至于更一般情况下,n次spfa的复杂度和Floyd哪个更高,还请大佬们指教(但这样Floyd这样不就没什么用了么....
#include<iostream>
#include<cstdio>
#include<vector>
#include<set>
#include<map>
#include<string.h>
#include<cmath>
#include<algorithm>
#include<queue>
#define LL long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
const int MAXV = 1010 ;
vector<int> g[MAXV] ;
bool vis[MAXV] ;
int dis[MAXV] ;
int n ;
int bfs(int u){
queue<int> p ;
int ans = 0 ;
while(!p.empty()) p.pop() ;
for(int i = 0 ; i < n ; i ++ ) {
vis[i] = 0 ; dis[i] = inf ;
}
vis[u] = true , dis[u] = 0 ; p.push(u) ;
while(!p.empty()){
int t = p.front() ; p.pop() ;
for(int i = 0 ; i < g[t].size() ; i ++ ){
int e = g[t][i] ;
if(vis[e]) continue ;
vis[e] = true ;
if(dis[e] > dis[t] + 1) dis[e] = dis[t] + 1 ;
p.push(e) ;
}
}
for(int i = 0 ; i < n ; i ++ ){
ans = max(ans , dis[i]) ;
}
if(ans == inf) return -1 ;
return ans ;
}
map<string , int> pq ;
int main()
{
int t, pos = 1 ; string read , read2;
while( ~ scanf("%d" , &n) && n){
pos = 0 ;
for(int i = 0 ; i < n ; i ++ ) g[i].clear() ;
for(int i = 0 ; i < n ; i ++ ){
cin >> read ;
pq[read] = pos ++ ;
}
int m , a , b ; scanf("%d" , &m) ;
if(m == 0 ) {printf("-1\n") ; continue ;}
for(int i = 0 ; i < m ; i ++){
cin >> read >> read2 ;
a = pq[read] , b = pq[read2] ;
g[a].push_back(b) ; g[b].push_back(a) ;
}
int res = 0 ;
int flag = 0 ;
for(int i = 0 ; i < n ; i ++ ){
int temp = bfs(i) ;
if(temp == -1) {flag = 1 ; break ;}
res = max(res , temp );
}
if(flag) printf("-1\n") ;
else printf("%d\n" , res);
}
return 0;
}
can you hear me?