T1 最短路径

思路:用邻接矩阵建图,很简单的用floyd求最短路
而记录路径时则要用二维,每次更新路径要在找到更优解的时候更新,pre[i][j]=k表示从i到j要经历的中转点为k,最后递归print
AC code
#include <bits/stdc++.h>
#define INF 1000000
const int maxn = 105;
using namespace std;
int a[maxn][maxn];
int n;
int dp[maxn][maxn];
int pre[maxn][maxn];
void print(int temp1, int temp2) {
// if(pre[temp])print(pre[temp]);
// printf("%d ",temp);
if (temp1 == temp2) {
printf("%d ", temp1);
return;
}
int path = pre[temp1][temp2];
if (path)
print(temp1, path);
printf("%d ", temp2);
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j) {
scanf(

这篇博客主要探讨了如何在动态规划过程中记录最短路径。在T1问题中,通过邻接矩阵建模并使用Floyd算法求解,利用二维数组pre更新和记录路径。在T2问题中,针对有向无环图,采用拓扑排序,同样利用pre数组更新最优路径,并在找到终点后递归输出前驱节点。两个问题都提供了AC代码。

1102

被折叠的 条评论
为什么被折叠?



