CF41D Pawn (线性dp)

题目链接

题意
在这里插入图片描述

这道题是很简单的线性dp , 绿题 , 首先我们肯定要做二维的dp , 表示横坐标和纵坐标 , 但是题目又给了一个只有整除(k + 1) 的才能作为方案数 , (洛谷上的题解都是求总和为多少[没有意义的时间复杂度]),我的思路是横坐标为i, 纵坐标为j , 和 模 (k + 1) 为 z 的最大和 。

时间复杂度一个完美的时间复杂度(n * m * k ) 。

代码

// Problem: CF41D Pawn
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/CF41D
// Memory Limit: 250 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std ;

const int N = 1e2 + 10 , M = 15 ;

int f[N][N][M] ;
int dx[] = {0 , 1 , 0 , -1} ;
int dy[] = {1 , 0 , -1 , 0} ;
char s[N][N] ;
int n , m , k ;
int path[N] ;

int read()
{
	int res = 0 , flag = 1 ;
	char c = getchar() ;
	while(!isdigit(c))
	{
		if(c == '-') flag = -1  ;
		c = getchar() ;
	}
	while(isdigit(c))
	{
		res = (res << 1) + (res << 3) + (c ^ 48) ;
		c = getchar() ;
	}
	return res * flag ;
}

int get(int x)
{
	return (x % (k + 1) + (k + 1)) % (k + 1) ; 
}
int main(void)
{
	memset(f , -0x3f , sizeof f) ;
	n = read() , m = read() , k = read() ;
	for(int i = 1 ; i <= n ; i ++)
		scanf("%s" , s[i] + 1) ;
	for(int i = 0 ; i <= m + 1 ; i ++) f[n + 1][i][0] = 0 ;
	for(int i = n ; i ; i --)
		for(int j = 1 ; j <= m ; j ++)
			for(int p = 0 ; p <= k ; p ++)
			{
				int q = get(p - (s[i][j] - '0')) ;
				f[i][j][p] = max(f[i + 1][j - 1][q] , f[i + 1][j + 1][q]) + (s[i][j] - '0') ;
			}
	int res = -1 ;
	for(int i = 1 ; i <= m ; i ++) res = max(res , f[1][i][0]) ;
	printf("%d\n" , res) ;
	if(res == -1) return 0 ;
	int t = -1 , p = 0 ;
	for(int i = 1 ; i <= m ; i ++)
		if(f[1][i][0] == res)
		{
			t = i ;
			break ;
		} 
	for(int i = 1 ; i < n ; i ++)
	{
		int q = get(p - (s[i][t] - '0')) ;
		if(f[i + 1][t - 1][q] + (s[i][t] - '0') == f[i][t][p]) path[i] = 1 , t = t - 1 ;
		else path[i] = 0 , t = t + 1 ;
		p = q ; 
	}
	printf("%d\n" , t) ;
	for(int i = n - 1 ; i ; i --)
		if(!path[i])
			printf("%c" , 'L') ;
		else 
			printf("%c" , 'R') ;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值