HDU 4460 Friend Chains
题意是求,在一个联通图中,求所以点对之间的最短路,并求出这些最短路中最长的是多少。
用Floyd-Warshall是O(n^3),会超时的。用于稀疏图的Johnson算法我不会,所以不知到行不行。所以只有用N次BFS求最短路。
图用邻接表储存,BFS的时候注意标记,以便能跳出循环。这样的时间复杂度就会远远低于n^3了。
下面是代码:
1 #include<stdio.h> 2 #include<iostream> 3 using namespace std; 4 5 #include<math.h> 6 #include<algorithm> 7 #include<string> 8 #include<map> 9 #include<queue> 10 #define repA(p,q,i) for(int (i)=(p); (i)!=(q); ++(i) ) 11 #define repD(p,q,i) for(int (i)=(p); (i)!=(q); --(i) ) 12 #define repAE(p,q,i) for(int (i)=(p); (i)<=(q); ++(i) ) 13 #define repDE(p,q,i) for(int (i)=(p); (i)>=(q); --(i) ) 14 #define range 1010 15 16 int n,m; 17 int Gf[range][10010]; 18 int maxn,mint; 19 int deep[range]; 20 bool confirm[range]; 21 22 23 void build(); 24 bool BFS(int s); 25 int solve(); 26 27 int main() 28 { 29 while( scanf("%d",&n) != EOF ) 30 { 31 if(n == 0) break; 32 build(); 33 printf("%d\n",solve() ); 34 } 35 return 0; 36 } 37 38 int solve() 39 { 40 maxn = -0x3f3f3f3f ; 41 repAE(1,n,i) 42 { 43 if( BFS(i) ) 44 maxn = max(maxn, mint); 45 else 46 { 47 //printf("FailBFS\n"); 48 return -1; 49 } 50 } 51 return maxn; 52 } 53 54 bool BFS(int s) 55 { 56 int total=1; 57 mint = -0x3f3f3f3f; 58 repAE(1,n,i) 59 confirm[i]=true; 60 queue<int> gray; 61 gray.push(s); 62 deep[s]=0; 63 confirm[s]=false; 64 65 int u; 66 while( !gray.empty() ) 67 { 68 if(total == n) 69 { 70 //printf("Bingo!\n"); 71 return true; 72 } 73 u=gray.front(); 74 gray.pop(); 75 repAE(1,Gf[u][0],i) 76 { 77 if(confirm[Gf[u][i] ]) 78 { 79 gray.push(Gf[u][i]); 80 deep[Gf[u][i] ] = deep[u]+1; 81 confirm[Gf[u][i] ]=false; 82 ++total; 83 mint = max(mint, deep[Gf[u][i] ] ); 84 } 85 } 86 87 } 88 return false; 89 } 90 91 void build() 92 { 93 repAE(1,n,i) 94 Gf[i][0]=1; 95 string str; 96 map<string,int> gray; 97 repAE(1,n,i) 98 { 99 cin>>str; 100 gray[str]=i; 101 } 102 103 string str1,str2; 104 int p,q; 105 scanf("%d",&m); 106 repAE(1,m,i) 107 { 108 cin>>str1>>str2; 109 p = gray[str1]; 110 q = gray[str2]; 111 Gf[p][ Gf[p][0]++ ] = q; 112 Gf[q][ Gf[q][0]++ ] = p; 113 } 114 return ; 115 }
To Be The Best Of Yourself