博客
关于我
洛谷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/jsp/asp的区别
    查看>>
    php20个主流框架
    查看>>
    php301到https,虚拟主机设置自动301跳转到HTTPS
    查看>>
    php5 apache 配置
    查看>>
    php5 升级 php7 版本遇到的问题处理方法总结
    查看>>
    PHP5.3.3安装Mcrypt扩展
    查看>>
    PHP5.4 + IIS + Win2008 R2 配置
    查看>>
    PHP5.4 pfsocketopen函数判断sock是否存活的bug(由memcached引起)
    查看>>
    Redis从入门到精通
    查看>>
    PHP5.6.x编译报错:Don't know how to define struct flock on this system, set --enable-opcache=no
    查看>>
    php5ts.dll 下载_php5ts.dll下载
    查看>>
    php7
    查看>>
    PHP7 新特性
    查看>>
    PHP7+MySQL5.7+Nginx1.9. on Ubuntu 14.0
    查看>>
    php7.1.6 + redis
    查看>>
    php7中使用php_memcache扩展
    查看>>
    PHP7中十个需要避免的坑
    查看>>
    php7和PHP5对比的新特性和性能优化
    查看>>
    PHP7安装pdo_mysql扩展
    查看>>
    PHP7实战开发简单CMS内容管理系统(7) 后台登录架构 用户登录校验
    查看>>