首页 > 代码库 > zoj2750最短路

zoj2750最短路

#include <cstdio>#include <cstring>#include <algorithm>#include <climits>#include <string>#include <iostream>#include <map>#include <cstdlib>#include <list>#include <set>#include <queue>#include <stack>using namespace std;const int INF=1000000000;struct Node{    int x;int val;};struct cmp{    bool operator () (const Node &a,const Node &b)    {        return a.val>b.val;    }};int n;const int maxn=1111;int dis[maxn];int vis[maxn];int Map[maxn][maxn];void djs(int x){    for(int i=0;i<n;i++){        dis[i]=INF;    }    memset(vis,0,sizeof(vis));    dis[x]=0;vis[x]=1;    Node k; k.x=x;k.val=0;    priority_queue < Node ,vector<Node> ,cmp> q;    q.push(k);    while(!q.empty()){        Node k=q.top();q.pop();        int cur=k.x;vis[cur]=1;        for(int i=0;i<n;i++){            if(dis[i]>dis[cur]+Map[cur][i]){                dis[i]=dis[cur]+Map[cur][i];                if(!vis[i]){                    Node k; k.x=i;k.val=dis[i]; q.push(k);                }            }        }    }}int main(){   string b,beh[10000],pre[10000];    int val[10000];    while(cin>>n,n){        for(int i=0;i<n;i++)        for(int j=0;j<n;j++)        Map[i][j]=INF;        for(int i=0;i<n;i++){             int a;string b;cin>>a>>b;int len=b.length();             val[i]=a;pre[i]=b.substr(0,4);beh[i]=b.substr(len-4,4);        }      //  for(int i=0;i<n;i++)           // cout<<val[i]<<" "<<pre[i]<<" "<<beh[i]<<endl;        for(int i=0;i<n;i++){            for(int j=0;j<n;j++){                if(i==j) continue;                if(beh[i]==pre[j]){                    if(val[i]<Map[i][j])                    Map[i][j]=val[i];//printf("%d %d %d",i,j,val[i]);system("pause");                }            }        }        djs(0);        if(dis[n-1]==INF)            cout<<-1<<endl;        else cout<<dis[n-1]<<endl;    }    return 0;}