题意分析:
(1)给出城市自行车租赁点分布以及路线,找到从PBMC出发到达需要调整目标点的最短路径,同时保证在调整这条路径上所有站点的自行车数时,出发时携带的自行车最少,如过不止一条,需要找出返回时携带最少自行车的最佳路线
(2)PAT中这种类型的题目比较常见,经常是从出发点到目标点求出最短路径,无非是在最佳路径上做出一些新花样,保证什么量最少,什么量最多,可以参考1003,也是同类型的题目,这类题目往往都是采用深度优先搜索,然后动态更新最短路径的同时,检查目标变量是否需要被修改等等,同时需要注意这些量并不是全局的,而是有依赖关系的,所以更新的时候要额外注意。
(3)此题的特殊性在于计算需要从出发点携带多少车辆是需要顺序地从最短路径的出发点到目标点遍历,在调整的过程中缺少自行车最多的就是最终从PBMC需要携带的量
可能坑点:
(1)这里从出发点最少携带量和最少回收量都不是全局的,最少携带量是依赖最短路径的,最少回收量是依赖在最短路径和最少携带量的;因此当最短路径被更新的时候,最少携带量和最少回收量都需要被强制更新。最少携带量被更新的时候,最少回收量也需要强制更新
#include <iostream>
#include <string.h>
#include <limits.h>
using namespace std;
int C,N,S,M;
int map[501][501]={-1};
int bikes[501];
int visit[501]={0};
int minPath[501]={0};
int nextStation[501]={0};
int length=0;
int minLength=INT_MAX;
int send,colect;
int minSend=INT_MAX,minColect=INT_MAX;
void getSendAndColect(int nextStation[])
{
colect=0;
send=INT_MAX;
int i=0;
while(i!=S)
{
colect+=bikes[nextStation[i]]-C/2;
if(colect<send)send=colect;
i=nextStation[i];
}
send=send<0?-send:0;
colect+=send;
colect=colect>0?colect:0;
}
//深度优先遍历
void DFS(int start,int end)
{
if(start==end)
{
if(length<=minLength)
{
getSendAndColect(nextStation);
if(length<minLength)
{
minLength=length;
minSend=send;
minColect=colect;
memcpy(minPath,nextStation,sizeof(nextStation));
}
else
{
if(send<=minSend)
{
if(send<minSend)
{
minSend=send;
minColect=colect;
memcpy(minPath,nextStation,sizeof(nextStation));
}
else
{
if(colect<minColect)
{
minColect=colect;
memcpy(minPath,nextStation,sizeof(nextStation));
}
}
}
}
}
return;
}
for(int i=1;i<=N;i++)
{
if(map[start][i]&&!visit[i])
{
visit[i]=1;
nextStation[start]=i;
length+=map[start][i];
DFS(i,end);
visit[i]=0;
length-=map[start][i];
}
}
}
//打印最佳路径
void printPath(int minPath[],int Sp)
{
int i=0;
while(i!=Sp)
{
cout<<i<<"->";
i=minPath[i];
}
cout<<i;
}
int main()
{
cin>>C>>N>>S>>M;
int i=1;
while(i<=N)cin>>bikes[i++];
int j=0;
int from,to,cost;
while(j<M)
{
cin>>from>>to>>cost;
map[from][to]=cost;
map[to][from]=cost;
j++;
}
DFS(0,S);
cout<<minSend<<" ";
printPath(minPath,S);
cout<<" "<<minColect<<endl;
return 0;
}