专题:在dp过程中记录路径

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

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

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(

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值