题意分析:
(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;
}