1030 Travel Plan (30 分)(最短路径 and dfs)

#include<bits/stdc++.h>

using namespace std;
const int N=510;
const int inf=0x3f3f3f3f;
int mp[N][N];
bool vis[N];
int dis[N];
int n,m,s,D;
int cost[N][N];
vector<int>path[N];
void Dijkstra()
{
    fill(vis,vis+N,false);
    fill(dis,dis+N,inf);
    for(int i=0;i<n;i++) dis[i]=mp[s][i];
    dis[s]=0;
    for(int i=0;i<n-1;i++){
        int u=-1;
        int minn=inf;
        for(int j=0;j<n;j++){
            if(!vis[j]&&dis[j]<minn){
                u=j;
                minn=dis[j];
            }
        }
        if(u==-1) return;
        vis[u]=true;
        for(int j=0;j<n;j++){
            if(!vis[j]&&dis[u]+mp[u][j]<=dis[j]){
                if(mp[u][j]+dis[u]<dis[j]){
                    dis[j]=mp[u][j]+dis[u];
                    path[j].clear();
                    path[j].push_back(u);
                }
                else{
                    path[j].push_back(u);
                }
            }
        }

    }
}
vector<int>t,p;
int minn=inf;
void dfs(int v)
{

    if(v==s){
        t.push_back(v);
        int sum=0;
        for(int i=t.size()-1;i>0;i--){
            int a=t[i];
            int b=t[i-1];
            sum+=cost[a][b];
        }
        if(sum<minn){
            minn=sum;
            p=t;
        }
        t.pop_back();
        return;
    }
    t.push_back(v);
    for(int i=0;i<path[v].size();i++){
        dfs(path[v][i]);
    }
    t.pop_back();

}
int main()
{
    fill(cost[0],cost[0]+N*N,0);
    fill(mp[0],mp[0]+N*N,inf);
    scanf("%d %d %d %d",&n,&m,&s,&D);
    while(m--){
        int a,b,c,d;
        scanf("%d %d %d %d",&a,&b,&c,&d);
        mp[a][b]=mp[b][a]=c;
        cost[a][b]=cost[b][a]=d;
    }
    Dijkstra();
    dfs(D);
    for(int i=p.size()-1;i>=0;i--){
        printf("%d ",p[i]);
    }
    printf("%d %d\n",dis[D],minn);
    return 0;
}

 

posted @ 2018-12-16 18:22  12-num  阅读(411)  评论(0编辑  收藏  举报