pat1030Travel Plan (30)

56 篇文章 0 订阅

题意分析:

(1)给出城市的的地图分布以及道路距离和每条道路的开销,给出出发点到目的地,找出最短路径,若有多条这样的路径,选择开销最小的

(2)这种题目已经不是什么难题了,之前的有很多这样的题目,参考1003(Emergency)、1018(Public Bike Management),都是深度优先,然后回溯,更新当前最短路径,而且由于开销并不是全局的,所以当最短路径更新的时候,开销要强制更新,注意到变量的依赖关系就不会出错

可能坑点:

(1)注意回溯时要更改访问标记

#include <iostream>
#include <limits.h>
#include <string.h>
#include <stdio.h>
using namespace std;

int map[501][501];
int cost[501][501];
int visit[501]={0};
int nextCity[501]={-1};
int path[501]={-1};
int N,M,S,D;
int minLength=INT_MAX;
int minCost=INT_MAX;
int currentLength=0;
int currentCost=0;

void printPath(int start,int end)
{
    while(start!=end)
    {
        printf("%d ",start);
        start=path[start];
    }
    cout<<end;
}

void DFS(int start,int end)
{
    if(start==end)
    {
        if(currentLength<=minLength)
        {
            if(currentLength<minLength)
            {
                minLength=currentLength;
                minCost=currentCost;
                memcpy(path,nextCity,sizeof(path));
            }
            else
            {
                if(currentCost<minCost)
                {
                    minCost=currentCost;
                    memcpy(path,nextCity,sizeof(path));
                }
            }
        }
    }
    for(int i=0;i<N;i++)
    {
        if(map[start][i]&&!visit[i])
        {
            visit[i]=1;
            currentLength+=map[start][i];
            currentCost+=cost[start][i];
            nextCity[start]=i;
            DFS(i,end);
            currentCost-=cost[start][i];
            currentLength-=map[start][i];
            visit[i]=0;
        }
    }
}

int main()
{
    memset(map,0,sizeof(map));
    memset(cost,0,sizeof(cost));
    scanf("%d %d %d %d",&N,&M,&S,&D);
    int i=0;
    int from,to,length,costs;
    while(i<M)
    {
        scanf("%d %d %d %d",&from,&to,&length,&costs);
        map[from][to]=length;
        map[to][from]=length;
        cost[from][to]=costs;
        cost[to][from]=costs;
        i++;
    }
    visit[S]=1;//这里尤其需要注意,防止递归循环
    DFS(S,D);
    printPath(S,D);
    printf(" %d %d\n",minLength,minCost);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值