一、技术总结
- 这一题,题意的理解十分关键,主要有两个点,在花费时间最少的前提下,一个是在去的路上进行调整,能够带的单车最少优先;如果还是有多条,那么带回单车最少的优先。说明只能在去的路上对车站的车进行调整,回的时候不能够进行调整,试想如果回的时候也可以调整,那么就不会出现第二个限制条件了。
- 使用Djikstra+DFS
- 同时在每个车站的车数量输入,进行减去Cmax/2,直接对于操作,方便后续操作。具体参考代码处
- 对于每个车站多了两个属性,一个是need,一个是remain,need记录到该车站处所欠缺的数量,也就是需要从管理中心调过来车的数量;remain记录到该车站处,多余的车,也就是往回运的车。
二、参考代码
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 510;
const int INF = 0x3fffffff;
int G[MAXN][MAXN];
int d[MAXN], weight[MAXN], w[MAXN];
vector<int> path, tempPath;
vector<int> pre[MAXN];
bool vis[MAXN] = {false};
int Cmax, n, s, m;
int minNeed = INF, minRemain = INF;
void Djikstra(int s){
fill(d, d+MAXN, INF);
d[s] = 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){
u = j;
MIN = d[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]){
d[v] = d[u] + G[u][v];
pre[v].clear();
pre[v].push_back(u);
}else if(d[u] + G[u][v] == d[v]){
pre[v].push_back(u);
}
}
}
}
}
void DFS(int v){
if(v == 0){
tempPath.push_back(v);
int need = 0, remain = 0;
for(int i = tempPath.size()-1; i >= 0; i--){
int id = tempPath[i];
if(weight[id] > 0){
remain += weight[id];
}else{
if(remain > abs(weight[id])){
remain -= abs(weight[id]);
}else{
need += abs(weight[id]) - remain;
remain = 0;
}
}
}
if(need < minNeed){//优化,如果所需的更少
minNeed = need;
minRemain = remain;
path = tempPath;
}else if(need == minNeed && remain < minRemain){
//携带数目相同,带回数目变多
minRemain = remain;
path = tempPath;
}
tempPath.pop_back();
return;
}
tempPath.push_back(v);
for(int i = 0; i < pre[v].size(); i++){
DFS(pre[v][i]);
}
tempPath.pop_back();
}
int main(){
scanf("%d%d%d%d", &Cmax, &n, &s, &m);
fill(G[0], G[0]+MAXN*MAXN, INF);
//weight[0] = 0;
for(int i = 1; i <= n; i++){
scanf("%d", &weight[i]);
weight[i] -= Cmax/2;
}
int id1, id2, L;
for(int i = 0; i < m; i++){
scanf("%d%d%d", &id1, &id2, &L);
G[id1][id2] = L;
G[id2][id1] = L;
}
Djikstra(0);
DFS(s);
int number = path.size()-1;
printf("%d ", minNeed);
for(int i = path.size()-1; i >= 0; i--){
printf("%d", path[i]);
if(i > 0) printf("->");
}
printf(" %d", minRemain);
return 0;
}