动态规划算法:多阶段决策问题——最短路径,c++代码
时间: 2024-06-10 20:02:27 浏览: 163
动态规划是一种解决多阶段决策问题的算法,其基本思想是将问题分解成一系列子问题,通过求解子问题的最优解来得到原问题的最优解。最短路径问题就是一种典型的多阶段决策问题,它的目标是在给定的有向加权图中找到一条从起点到终点的路径,使得路径上所有边的权值之和最小。
下面是该问题的一种动态规划算法:
```c++
#include <iostream>
#include <vector>
using namespace std;
const int MAXN = 1005;
const int INF = 0x3f3f3f3f;
int n, m, s, t;
int dis[MAXN], vis[MAXN], pre[MAXN];
vector<pair<int, int>> g[MAXN];
void dijkstra(int s) {
for (int i = 1; i <= n; ++i) {
dis[i] = INF;
vis[i] = 0;
}
dis[s] = 0;
for (int i = 1; i < n; ++i) {
int u = -1, minn = INF;
for (int j = 1; j <= n; ++j) {
if (!vis[j] && dis[j] < minn) {
u = j;
minn = dis[j];
}
}
if (u == -1) break;
vis[u] = 1;
for (int j = 0; j < g[u].size(); ++j) {
int v = g[u][j].first, w = g[u][j].second;
if (!vis[v] && dis[u] + w < dis[v]) {
dis[v] = dis[u] + w;
pre[v] = u;
}
}
}
}
void dfs(int u) {
if (u == s) {
cout << s << " ";
return;
}
dfs(pre[u]);
cout << u << " ";
}
int main() {
cin >> n >> m >> s >> t;
for (int i = 1; i <= m; ++i) {
int u, v, w;
cin >> u >> v >> w;
g[u].push_back(make_pair(v, w));
}
dijkstra(s);
if (dis[t] == INF) cout << "No solution!";
else {
cout << "The shortest path is: ";
dfs(t);
cout << "\nThe length of the shortest path is: " << dis[t];
}
return 0;
}
```
阅读全文