hdu2112最短路径

主要是对字符串的处理,脑袋木了一下

#include <cstdlib>
#include <iostream>
#include<string>
#include<vector>
#include<queue>
using namespace std;

struct edge
{
    int from,to;
    int cost;
};
const int MAXN=155;
const int MAX=0xfffffff;
bool in_queue[MAXN];
int dist[MAXN];
vector<edge>v[MAXN];
string location[MAXN];
int tag=0;
int locate(string s)
{
    int i=0;
    for(i=0;i<=tag-1;i++)
    {
        if(s==location[i])
        {
            return i;
        }
    }
    location[tag]=s;
    tag++;
    return tag-1;
}
void spfa(int p)
{
    queue<int>q;
    int i=0;
    int cur;
    while(!q.empty())
    {
        q.pop();
    }
    q.push(p);
    dist[p]=0;
    in_queue[p]=1;
    while(!q.empty())
    {
        int i=0;
        int cost,to;
        cur=q.front();
        q.pop();
        
        for(i=0;i<=int(v[cur].size())-1;i++)
        {
            cost=v[cur][i].cost+dist[cur];
            to=v[cur][i].to;
            if(cost<dist[to])
            {
                dist[to]=cost;
                if(!in_queue[to])
                {
                    q.push(to);
                    in_queue[to]=1;
                }
            }
        }
        in_queue[cur]=0;
    }
    return;
}
int main(int argc, char *argv[])
{
    int n;
    while((cin>>n)&&(n!=-1))
    {
        string start,end;
        int i=0;
        int idx=0;
         tag=0;
         for(i=0;i<=MAXN-1;i++)
         {
            location[i]="";
        }
        memset(in_queue,0,sizeof(in_queue));
        for(i=0;i<=MAXN-1;i++)
        {
            dist[i]=MAX;
        }
        for(i=0;i<=MAXN-1;i++)
        {
            v[i].clear();
        }
        cin>>start>>end;
        locate(start);
        locate(end);
        for(i=0;i<=n-1;i++)
        {
            string s1,s2;
            int cost;
            int from,to;
            cin>>s1>>s2>>cost;
            from=locate(s1);
            to=locate(s2);
            edge e={from,to,cost};
            v[e.from].push_back(e);
            swap(e.from,e.to);
            v[e.from].push_back(e);
        }
        spfa(locate(start));
        /*
        for(int jjj=0;jjj<=MAXN-1;jjj++)
        {
            cout<<dist[jjj]<<" ";
        }*/
        if(dist[locate(end)]<MAX)
        {
            cout<<dist[locate(end)]<<endl;
        }else
        {
            cout<<-1<<endl;
        }
    }
    //system("PAUSE");
    return EXIT_SUCCESS;
}

  

原文地址:https://www.cnblogs.com/cj695/p/2609483.html