#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int maxn = 5e2 + 5, inf = 1e9;
int n,m,cmax,ed,w[maxn],g[maxn][maxn];
int minsent = inf, minback = inf;
vector<vector<int>> path(maxn);
vector<int> p,ans;
ostream& operator<<(ostream &os, vector<int> &v)
{
for (int i = v.size() - 1; i >= 0; i--)
{
os << v[i];
if (i > 0)
os << "->";
}
return os;
}
void DFS(int now, int ed)
{
if (now == ed)
{
int sent = 0, back = 0; //路径从头到尾计算sent和back
for (int i = p.size() - 2; i >= 0; i--)
{
int x = p[i];
if (w[x] >= 0)
back += w[x];
else
{
if (back >= abs(w[x]))
back += w[x];
else
{
sent += abs(w[x]) - back;
back = 0;
}
}
}
if (sent < minsent || sent == minsent&&back < minback)
{
minsent = sent;
minback = back;
ans = p;
}
}
for (auto &pre : path[now])
{
p.push_back(pre);
DFS(pre, 0);
p.pop_back();
}
}
void dijkstra(int st)
{
priority_queue<pii, vector<pii>, greater<pii>> q;
vector<int> vis(maxn, 0), d(maxn, inf);
d[st] = 0;
q.push({ 0,st });
while (!q.empty())
{
auto top = q.top();
q.pop();
int u = top.second;
if(vis[u])
continue;
for (int i = 0; i <= n; i++)
{
if(vis[i]||g[u][i]==inf)
continue;
if (d[i] > d[u] + g[u][i])
{
d[i] = d[u] + g[u][i];
path[i].clear();
path[i].push_back(u);
q.push({ d[i],i });
}
else if (d[i] == d[u] + g[u][i])
path[i].push_back(u);
}
}
p.push_back(ed);
DFS(ed, 0);
cout << minsent << " " << ans << " " << minback;
}
int main()
{
cin >> cmax >> n >> ed >> m;
fill(g[0], g[0] + maxn*maxn, inf);
for (int i = 1; i <= n; i++)
{
cin >> w[i];
w[i] -= cmax / 2;
}
for (int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
g[a][b] = g[b][a] = c;
}
dijkstra(0);
return 0;
}
1018 Public Bike Management (30 分)-Dijkstra+DFS多条最短路径问题
最新推荐文章于 2024-08-19 23:56:23 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)