【DP】【CF31E】 TV Game
Description
给你一个长度为的数字,每次可以从左侧选一个数字,加入连接到一个数字或另一个数字后面。初始为。与必须恰好被连接次。最大化的和,输出方案
Input
第一行是,第二行是长度为的数字
Output
从左到右输出该数字第几位被如何处理。连接到输出,连接到输出。
Hint
Solution
看起来像是个DP啊……
考虑如果正向DP的话,每次选择一个数,数字和增加多少依赖于之前那个数字选了多少。这显然是有后效性的,难以处理。
考虑反过来DP。
这样每次选一个数只依赖于之前选了多少位,可以直接设到状态里面。于是可以设为选了位,选了位的数字和,转移显然。
Code
#include<cstdio>
#define rg register
#define ci const int
#define cl const long long
typedef long long int ll;
template <typename T>
inline void qr(T &x) {
rg char ch=getchar(),lst=' ';
while((ch > '9') || (ch < '0')) lst=ch,ch=getchar();
while((ch >= '0') && (ch <= '9')) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
if(lst == '-') x=-x;
}
namespace IO {
char buf[120];
}
template <typename T>
inline void qw(T x,const char aft,const bool pt) {
if(x < 0) {x=-x,putchar('-');}
rg int top=0;
do {IO::buf[++top]=x%10+'0';} while(x/=10);
while(top) putchar(IO::buf[top--]);
if(pt) putchar(aft);
}
template <typename T>
inline T mmax(const T a,const T b) {return a > b ? a : b;}
template <typename T>
inline T mmin(const T a,const T b) {return a < b ? a : b;}
template <typename T>
inline T mabs(const T a) {return a < 0 ? -a : a;}
template <typename T>
inline void mswap(T &_a,T &_b) {
T _temp=_a;_a=_b;_b=_temp;
}
const int maxn = 40;
const int INF = 0x3f3f3f3f;
int n,dn;
int MU[maxn];
ll frog[maxn][maxn],ten[maxn]={1};
char s[maxn];
bool pre[maxn][maxn];
void dfs(ci,ci);
int main() {
qr(n);
scanf("%s",s+1);
dn=n<<1;
for(rg int i=dn;i;--i) MU[dn-i+1]=s[i]-'0';
for(rg int i=1;i<n;++i) ten[i]=ten[i-1]*10ll;
for(rg int i=0;i<maxn;++i) for(rg int j=0;j<maxn;++j) frog[i][j]=-INF;
frog[0][0]=0;
for(rg int i=0;i<=n;++i) {
for(rg int j=0;j<=n;++j) {
int len=i+j;
if(i) frog[i][j]=frog[i-1][j]+MU[len]*ten[i-1];
if(j) {
if(frog[i][j] < frog[i][j-1]+MU[len]*ten[j-1]) {
frog[i][j]=frog[i][j-1]+MU[len]*ten[j-1];pre[i][j]=true;
}
}
}
}
dfs(n,n);
putchar('\n');
return 0;
}
void dfs(ci x,ci y) {
if((!x) && (!y)) return;
if(pre[x][y]) {putchar('H');dfs(x,y-1);}
else {putchar('M');dfs(x-1,y);}
}
Summary
在序列上的线性DP,当正向难以转移时,可以考虑反向DP。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具