hdu 2112 map+Dijkstra

无向图 用map 起点和终点可能一样 数组不能开太大 WA了好多发

Sample Input
6
xiasha westlake //起点 终点
xiasha station 60
xiasha ShoppingCenterofHangZhou 30
station westlake 20
ShoppingCenterofHangZhou supermarket 10
xiasha supermarket 50
supermarket westlake 10
-1

Sample Output
50

 

  1 # include <iostream>
  2 # include <cstdio>
  3 # include <cstring>
  4 # include <string>
  5 # include <algorithm>
  6 # include <cmath>
  7 # include <queue>
  8 # include <map>
  9 # define LL long long
 10 using namespace std ;
 11 
 12 const int INF=0x3f3f3f3f;
 13 const int MAXN=1010;
 14 
 15 int n ;
 16 map<string,int> mp ;
 17 bool vis[MAXN];
 18 int cost[MAXN][MAXN] ;
 19 int lowcost[MAXN] ;
 20 
 21 
 22 void Dijkstra(int beg)
 23 {
 24     for(int i=0;i<n;i++)
 25     {
 26         lowcost[i]=INF;vis[i]=false;
 27     }
 28     lowcost[beg]=0;
 29     for(int j=0;j<n;j++)
 30     {
 31         int k=-1;
 32         int Min=INF;
 33         for(int i=0;i<n;i++)
 34             if(!vis[i]&&lowcost[i]<Min)
 35             {
 36                 Min=lowcost[i];
 37                 k=i;
 38             }
 39             if(k==-1)
 40                 break ;
 41             vis[k]=true;
 42             for(int i=0;i<n;i++)
 43                 if(!vis[i]&&lowcost[k]+cost[k][i]<lowcost[i])
 44                 {
 45                     lowcost[i]=lowcost[k]+cost[k][i];
 46 
 47                 }
 48     }
 49 
 50 }
 51 
 52 int main ()
 53 {
 54    // freopen("in.txt","r",stdin) ;
 55    int m ;
 56    while(cin>>m)
 57    {
 58        if (m == -1)
 59         break ;
 60        mp.clear() ;
 61        string s1 ,s2 ;
 62        int i , j , w ;
 63        for (i = 0 ; i < MAXN ; i++)
 64         for (j = 0 ; j < MAXN ; j++)
 65        {
 66            if (i == j)
 67               cost[i][j] = 0 ;
 68            else
 69               cost[i][j] = INF ;
 70        }
 71 
 72 
 73        cin>>s1>>s2 ;
 74        mp[s1] = 1 ;
 75        mp[s2] = 2 ;
 76        n = 3 ;
 77        bool flag = 0 ;
 78        if (s1 == s2)
 79           flag = 1 ;
 80        while(m--)
 81        {
 82            cin>>s1>>s2>>w ;
 83            if (!mp[s1])
 84                mp[s1] = n++ ;
 85            if (!mp[s2])
 86                mp[s2] = n++ ;
 87            if (w < cost[mp[s1]-1][mp[s2]-1])
 88            {
 89                cost[mp[s1]-1][mp[s2]-1] = w ;
 90                cost[mp[s2]-1][mp[s1]-1] = w ;
 91            }
 92 
 93        }
 94        n-- ;
 95        if (flag)
 96        {
 97            cout<<0<<endl ;
 98            continue ;
 99        }
100        Dijkstra(0) ;
101 
102        if (lowcost[1] != INF)
103           cout<<lowcost[1]<<endl ;
104        else
105           cout<<-1<<endl ;
106 
107    }
108 
109 
110 
111 
112     return 0 ;
113 }
View Code

 

posted @ 2015-06-20 16:18  __Meng  阅读(151)  评论(0编辑  收藏  举报