1087 All Roads Lead to Romne (30 分)字符串转化+dijkstra+dfs

当标尺比较多的时候,可以用dijkstra+dfs,这样dijkstra只需要找出最短路径下所有的pre即可,然后在dfs中便利这些路径,在单独由第二标尺第三标尺找出最佳路径

#include
using namespace std;
const int MAXN=210;
const int INF=100000000;
int n,m,st,G[MAXN][MAXN],weight[MAXN];
int d[MAXN],numpath=0,maxw=0;
double maxavg=0;
bool vis[MAXN]={false};
vector<int> pre[MAXN];
vector<int> temppath,path;
map<string,int> citytoid;
map<int,string> idtocity;
void dijkstra(int s){
    fill(d,d+MAXN,INF);
    d[s]=0;
    for(int i=0;i<n;i++){
        int u=-1,min=INF;
        for(int j=0;j<n;j++){
            if(vis[j]==false&&d[j]<min){
                min=d[j];
                u=j;
            }
        }
        if(u==-1)  return;
        vis[u]=true;
        for(int v=0;v<n;v++){
            if(vis[v]==false&&G[u][v]!=INF){
                if(d[u]+G[u][v]<d[v]){
                    d[v]=d[u]+G[u][v];
                    pre[v].clear();
                    pre[v].push_back(u);
                }
                else if(d[u]+G[u][v]==d[v]){
                    pre[v].push_back(u);
                }
            }
        }
    }
}
void dfs(int v){
    if(v==st){
        temppath.push_back(v);
        numpath++;
        int tempw=0;
        for(int i=temppath.size()-2;i>=0;i--){
            int id=temppath[i];
            tempw+=weight[id];
        }
        double tempavg=1.0*tempw/(temppath.size()-1);
        if(tempw>maxw){
            maxw=tempw;
            path=temppath;
            maxavg=tempavg;
        }
        else if(tempw==maxw&&tempavg>maxavg){
            maxavg=tempavg;
            path=temppath;
        }
        temppath.pop_back();
        return;
    }
    temppath.push_back(v);
    for(int i=0;i<pre[v].size();i++){
        dfs(pre[v][i]);
    }
    temppath.pop_back();
}                   
int main(){
    string start,city1,city2;
    cin>>n>>m>>start;
    citytoid[start]=0;
    idtocity[0]=start;
    for(int i=1;i<n;i++){
        cin>>city1>>weight[i];
        citytoid[city1]=i;
        idtocity[i]=city1;
    }
    fill(G[0],G[0]+MAXN*MAXN,INF);
    for(int i=0;i<m;i++){
        cin>>city1>>city2;
        int c1=citytoid[city1],c2=citytoid[city2];
        cin>>G[c1][c2];
        G[c2][c1]=G[c1][c2];
    }
    dijkstra(0);
    int rom=citytoid["ROM"];
    dfs(rom);
    cout<<numpath<<" "<<d[rom]<<" "<<maxw<<" "<<(int)maxavg<<endl;
    for(int i=path.size()-1;i>=0;i--){
        cout<<idtocity[path[i]];
        if(i>0) cout<<"->";
    }
    return 0;
}

你可能感兴趣的:(pat,dfs,dijkstra)