博客
关于我
洛谷P1004方格取数(四维DP)
阅读量:252 次
发布时间:2019-03-01

本文共 2413 字,大约阅读时间需要 8 分钟。

为了解决这个问题,我们需要找到从矩阵的左上角(1,1)走到右下角(n,n)的两条路径,使得第一次路径经过的所有方格的值变为0。然后,第二条路径经过的方格的值之和最大。

方法思路

为了找到最优解,我们可以使用四维动态规划(DP)来解决这个问题。四维DP数组dp[i][j][k][t]表示第一个人从(1,1)走到(i,j),第二个人从(1,1)走到(k,t)的最大值。状态转移方程考虑了从上方和左方来的路径,并确保在相同点上不重复计算值。

解决代码

#include 
using namespace std;void read(T &x) { T res = 0, f = 1; char c = getchar(); while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); } while (isdigit(c)) { res = (res < 3) ? (res < 1 ? res * 10 + c - '0' : res * 10 + c - '0') : (res * 10 + c - '0') * 10 + c - '0'; c = getchar(); } x = res * f;}void print(ll x) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) print(x / 10); putchar(x % 10 + '0');}const int maxn = 10;const ll mod = 1e9 + 7;ll n, mp[maxn][maxn];ll dp[maxn][maxn][maxn][maxn];ll gcd(ll a, ll b) { return (b == 0) ? a : gcd(b, a % b);}ll qpow(ll a, ll p, ll mod) { ll ans = 1; a %= mod; while (p) { if (p & 1) ans = (ans * a) % mod; a = (a * a) % mod; p >>= 1; } return ans;}ll ksm(ll a, ll b) { ll ret = 1; while (b) { if (b & 1) ret = (ret * a) % mod; a = (a * a) % mod; b >>= 1; } return ret;}int main() { int T = 1; while (T--) { read(n); while (scanf("%lld%lld%lld%lld", &x, &y, &k) != EOF) { if (x == 0 && y == 0 && k == 0) break; mp[x][y] = k; } for (ll i = 1; i <= n; ++i) { for (ll j = 1; j <= n; ++j) { for (ll k = 1; k <= n; ++k) { for (ll t = 1; t <= n; ++t) { ll option1 = dp[i-1][j][k-1][t]; ll option2 = dp[i-1][j][k][t-1]; ll option3 = dp[i][j-1][k-1][t]; ll option4 = dp[i][j-1][k][t-1]; ll max_opt = max(option1, option2, option3, option4); ll current_sum = max_opt + mp[i][j] + mp[k][t]; if (i == k && j == t) { current_sum -= mp[i][j]; } dp[i][j][k][t] = current_sum; } } } } cout << dp[n][n][n][n] << endl; }}

代码解释

  • 读取输入:读取矩阵大小和矩阵值。
  • 初始化DP数组:创建四维DP数组dp,用于存储状态转移结果。
  • 状态转移:对于每一个状态,计算从上方和左方来的最大值,并确保在相同点上不重复计算值。
  • 输出结果:输出DP数组在终点的值,即两条路径经过的值的最大和。
  • 这个方法通过四维动态规划有效地解决了问题,确保了两条路径在相同点上不重复计算值,从而找到最优解。

    转载地址:http://ihst.baihongyu.com/

    你可能感兴趣的文章
    php 子进程监听消息,swoole学习笔记之多线程端口监听问题记录 多进程epoll模式...
    查看>>
    PHP 学习笔记 (四)
    查看>>
    Redis入门概述
    查看>>
    php 实现Iterator 接口
    查看>>
    PHP 实现N阶矩阵相乘
    查看>>
    php 实现进制转换(二进制、八进制、十六进制)互相转换
    查看>>
    PHP 实现页面跳转的三种方式及详细解析
    查看>>
    php 将XML对象转化为数组
    查看>>
    PHP 工具
    查看>>
    php 常用方法
    查看>>
    PHP 并发扣款,保证数据一致性(悲观锁和乐观锁)
    查看>>
    php 延迟静态绑定static关键字
    查看>>
    php 引用 -
    查看>>
    Redis入门
    查看>>
    PHP 截取字符串乱码的解决方案
    查看>>
    php 接口类与抽象类的实际作用
    查看>>
    PHP 插入排序 -- 折半查找
    查看>>
    PHP 支持8种基本的数据类型
    查看>>
    php 放大镜,放大镜放大图片效果
    查看>>
    php 数据库 表格数据,php数据库到excel表格-php怎么把数据库数据放到表格里
    查看>>