最短路+dfs
好难啊~~~
用dijkstra找到所有的最短路路径并记录下来
用dfs找到最短路径中最合适的那一条
这两种的结合的方式要牢牢掌握~找到后输出即可
dfs 模拟车的搬运 很巧妙
#include <bits/stdc++.h>
using namespace std;
int graph[1000][1000];
#define MAXN 0x3f3f3f3f
int V[10200],vis[10200],dist[10200];
int Cmax,N,Sp,M,minNeed,minBack;
vector<int> pre[1024];
vector<int> path;
void init(){
cin>>Cmax>>N>>Sp>>M;
for(int i=1;i<=N;i++){
cin>>V[i];
V[i]-=Cmax/2;
}
memset(dist,MAXN,sizeof(dist));
memset(graph,0x3f,sizeof(graph));
minNeed=minBack=MAXN;
}
void dfs(int x, vector<int> temppath){
temppath.push_back(x);//终点
if(x==0){
int mNeed=0;
int mBack=0;
for(int i=temppath.size()-1;i>=0;i--){
int index=temppath[i];
if(V[index]>0){
mBack+=V[index];
}
else{//缺的
if(mBack+V[index]>0){//可以减轻负担
mBack+=V[index];
}
else{//啥都带不回去
mNeed+=-(mBack+V[index]);//可能还要多带几辆回来
mBack=0;
}
}
}
if(mNeed<minNeed){
minNeed=mNeed;
minBack=mBack;
path=temppath;
}
else if(mNeed==minNeed&&mBack<minBack){
minBack=mBack;
path=temppath;
}
return;
}
for(int i=0;i<pre[x].size();i++){
dfs(pre[x][i],temppath);
}
}
void dijkstra(){
dist[0]=0;
for(int j=0;j<=N;j++){
int k=-1;
int Min=MAXN;
for(int i=0;i<=N;i++){
if(!vis[i]&&dist[i]<Min){
Min=dist[i]; k=i;
}
}
if(k==-1)break;
vis[k]=true;
for(int i=0;i<=N;i++){
if(!vis[i]){
if(dist[k]+graph[k][i]<dist[i]){
dist[i]=dist[k]+graph[k][i];
pre[i].clear();
pre[i].push_back(k);
}
else if(dist[k]+graph[k][i]==dist[i]){
pre[i].push_back(k);
}
}
}
}
}
int main(){
init();
for(int i=1;i<=M;i++){
int a,b,cost;
cin>>a>>b>>cost;
graph[a][b]=graph[b][a]=cost;
}
dijkstra();
vector<int> temppath;
dfs(Sp,temppath);
printf("%d 0",minNeed);
for(int i=path.size()-2;i>=0;i--){
printf("->%d",path[i]);
}
printf(" %d",minBack);
return 0;
}