PAT甲1030 Travel Plan (30)(30 分)

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
using namespace std;

const int inf=1111111111;
int G[510][510];
int d[510],cost[510][510];
bool vis[510];
vector<int> pre[510];
int N,M,st,ed;

void Dij(int st)
{
    fill(vis,vis+510,false);
    fill(d,d+510,inf);
    d[st]=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])
                {
                    pre[v].clear();
                    pre[v].push_back(u);
                    d[v]=d[u]+G[u][v];
                }
                else if(d[u]+G[u][v]==d[v])
                {
                    pre[v].push_back(u);
                }
            }
        }
    }
}

int mincost=inf;
vector<int> path,temppath;

void DFS(int now)
{
    if(now==st)
    {
        temppath.push_back(now);
        int c=0;
        for(int i=1;i<temppath.size();i++)
        {
            int c1=temppath[i];
            int c2=temppath[i-1];
            c+=cost[c1][c2];
        }
        if(c<mincost)
        {
            mincost=c;
            path=temppath;
        }
        temppath.pop_back();
        return;
    }
    temppath.push_back(now);
    for(int i=0;i<pre[now].size();i++)
    {
        DFS(pre[now][i]);
    }
    temppath.pop_back();
}

int main()
{
    scanf("%d%d%d%d",&N,&M,&st,&ed);
    fill(G[0],G[0]+510*510,inf);
    for(int i=0;i<M;i++)
    {
        int c1,c2,l,c;
        scanf("%d%d%d%d",&c1,&c2,&l,&c);
        G[c1][c2]=l;
        G[c2][c1]=l;
        cost[c1][c2]=c;
        cost[c2][c1]=c;
    }
    Dij(st);
    DFS(ed);
    for(int i=path.size()-1;i>=0;i--)
    {
        printf("%d ",path[i]);
    }
    printf("%d %d",d[ed],mincost);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值