HDU 2112HDU Today(map+djkstra,一种挺有意思的组合)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2112

题目大意:其实如果将车站编号从英文换成数字,那么这道题就是非常简单的最短路问题了,所以这道题的窍门就是想办法把英文编号转换为数字编号;这道题意思就是给你一个起始车站和终点车站,通过转车站得到起始车站到终点车站的最短距离,若不能到达则输出-1;

上代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=110;
const int MAX=0x3f3f3f3f;
int book[maxn],mp[maxn][maxn];
void djk(int start ,int end){
    int i,j,k;
    for(i=0;i<end;i++){
        int mi=MAX,u;
        for(j=start;j<=end;j++){
            if(mp[start][j]<mi&&!book[j]){
                mi=mp[start][j];
                u=j;
            }
        }
        book[u]=1;
        for(k=start;k<=end;k++){
            if(mp[u][k]!=MAX){
                if(mp[start][k]>mp[start][u]+mp[u][k]){
                    mp[start][k]=mp[start][u]+mp[u][k];
                }
            }
        }
    }
}
int main()
{
    int n,i,j,k,x;
    map<string,int>sta;
        while(cin>>n&&n!=-1){
            sta.clear();//注意,此处不可少;
            memset(book,0,sizeof(book));
            memset(mp,MAX,sizeof(mp));
            string s1,s2;
            cin>>s1>>s2;//输入起始车站和终点车站;
        
        sta[s1]=1;sta[s2]=2;//令起点车站的编号为1,终点车站的编号为2;
        int ite=3;//声名一个变量表示其他车站的编号
        string str1,str2;
        for(i=0;i<n;i++){
            cin>>str1>>str2>>x;//输入路径;
            if(!sta[str1])//若该车站编号尚未转换成数字,将其转换成数字;
            sta[str1]=ite++;
            if(!sta[str2])//同上
            sta[str2]=ite++;
            mp[sta[str1]][sta[str2]]=x;//接下来就是一般的djkstra操作的,不详细述说了;
            mp[sta[str2]][sta[str1]]=x;
        }
        if(s1==s2){
            cout<<0<<endl;
            continue;
        }
        book[1]=1;
        djk(1,ite);
        if(mp[1][2]==MAX)
        cout<<-1<<endl;
        else
        cout<<mp[1][2]<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/k_r_forever/article/details/80500392