题意:一个有n个点,m条边的无向图,找出最短路中的两个点的路径最大值。

n次spfa求最短路,然后找出最大值即可,踩着时间线险过。。。

代码:

  1 #include <iostream>
  2 #include <cstring>
  3 #include <algorithm>
  4 #include <cstdio>
  5 #include <queue>
  6 #include <string>
  7 #include <map>
  8 using namespace std;
  9 
 10 const int oo=1<<30;
 11 const int maxn=1001;
 12 const int maxm=20001;
 13 int n,m,num;
 14 int cnt;
 15 int dis[maxn],head[maxn];
 16 bool vis[maxn];
 17 queue<int>qu;
 18 map<string, int> mp;
 19 struct node{
 20     int u;
 21     int v;
 22     int w;
 23     int next;
 24 }edge[maxm];
 25 
 26 void add(int u, int v, int w){
 27     edge[cnt].u=u;
 28     edge[cnt].v=v;
 29     edge[cnt].w=w;
 30     edge[cnt].next=head[u];
 31     head[u]=cnt++;
 32     edge[cnt].u=v;
 33     edge[cnt].v=u;
 34     edge[cnt].w=w;
 35     edge[cnt].next=head[v];
 36     head[v]=cnt++;
 37 }
 38 
 39 void spfa(int s){
 40     for(int i=0; i<n; i++){
 41         dis[i]=oo;
 42         vis[i]=false;
 43     }
 44     dis[s]=0;
 45     qu.push(s);
 46     vis[s]=true;
 47     while(!qu.empty()){
 48         int u=qu.front();
 49         qu.pop();
 50         vis[u]=false;
 51         for(int i=head[u];i!=-1;i=edge[i].next){
 52             int v=edge[i].v;
 53             if(dis[u]+edge[i].w<dis[v]){
 54                 dis[v]=dis[u]+edge[i].w;
 55                 if(!vis[v]){
 56                     vis[v]=true;
 57                     qu.push(v);
 58                 }
 59             }
 60         }
 61     }
 62 }
 63 
 64 void init(){
 65     while(!qu.empty()){
 66         qu.pop();
 67     }
 68     cnt=0;
 69     num=0;
 70     mp.clear();
 71     memset(head, -1, sizeof(head));
 72 }
 73 
 74 int main(){
 75     string str;
 76     string str1;
 77     while(~scanf("%d",&n)){
 78         init();
 79         if(n==0)
 80             break;
 81         for(int i=0; i<n; i++){
 82             cin>>str;
 83             mp[str]=i;
 84         }
 85         scanf("%d",&m);
 86         for(int i=0; i<m; i++){
 87             cin>>str>>str1;
 88             int u=mp[str];
 89             int v=mp[str1];
 90             add(u, v, 1);
 91         }
 92         for(int i=0; i<n; i++){
 93             spfa(i);
 94             for(int j=0; j<n; j++){
 95                 num=max(num,dis[j]);
 96             }
 97         }
 98         num=num==oo?-1:num;
 99         printf("%d\n",num);
100     }
101     return 0;
102 }
posted on 2012-11-09 11:32  pony1993  阅读(1305)  评论(11编辑  收藏  举报

View My Stats