当前位置: 首页 > news >正文

Array Description(Dynamic programming)

题目描述

You know that an array has n integers between 1 and  m, and the absolute difference between two adjacent values is at most 1.
Given a description of the array where some values may be unknown, your task is to count the number of arrays that match the description.

输入

The first input line has two integers n and m: the array size and the upper bound for each value.
The next line has n integers x1,x2,...,xn: the contents of the array. Value 0 denotes an unknown value.
Constraints
1 ≤ n ≤ 10^5
1 ≤ m ≤ 100
0 ≤ xi ≤ m

输出

Print one integer: the number of arrays modulo 10^9+7.

样例输入
3 5
2 0 2
样例输出
3
提示

The arrays [2,1,2], [2,2,2] and [2,3,2] match the description.

思路分析

dp_prev数组用于存储前一个位置的状态值。

对于数组  arr 中的每个位置  i(0-based indexing),分情况进行处理:

1.当 arr[i] = 0 时:

(1)如果 i = 0,即数组的第一个位置,此位置可以取区间 [1, m] 内的任意值,所以 dp_prev[j] 初始化为 1(其中 1 ≤ j ≤ m);

(2)若 i > 0,则需考虑前一位置的数值,通过遍历 j 从 1 到 m,计算当前位置 i 取值为 j 的可能性,即 dp_cur[j] = (dp_prev[j - 1] + dp_prev[j] + dp_prev[j + 1])%mod。

2.当 arr[i] ≠ 0 时,该位置只能取 arr[i] 这个值,所以 dp_cur[arr[i]] = (dp_prev[arr[i] - 1] + dp_prev[arr[i]] + dp_prev[arr[i] + 1] )%mod。

每处理完 arr 数组中的一个元素,就将 dp_prev 更新为 dp_cur,以保存当前位置的状态供后续使用。

最后,将 dp_prev 数组中从 1 到 m 的所有值累加并对 mod 取模,得到最终结果并输出。 

代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int mod=1e9+7;
int n,m;
int main(){ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);cin>>n>>m;vector<int>arr(n);for(int i=0;i<n;i++){cin>>arr[i];}vector<ll>dp_prev(m+2,0);if(arr[0]==0){for(int i=1;i<=m;i++){dp_prev[i]=1;}}else{dp_prev[arr[0]]=1;}for(int i=1;i<n;i++){vector<ll>dp_cur(m+2,0);if(arr[i]==0){for(int j=1;j<=m;j++){dp_cur[j]=(dp_prev[j-1]+dp_prev[j]+dp_prev[j+1])%mod;}}else{int k=arr[i];dp_cur[k]=(dp_prev[k-1]+dp_prev[k]+dp_prev[k+1])%mod;}dp_prev=dp_cur;}ll ans=0;for(int i=1;i<=m;i++){ans=(ans+dp_prev[i])%mod;}cout<<ans;return 0;
}

http://www.dtcms.com/a/321209.html

相关文章:

  • 【网络编程】IO多路转接——epoll
  • Java文件读写(IO、NIO)
  • 第39周——训练自己的数据集
  • 汇编语言和高级语言的差异
  • BGP综合实验练习作业
  • Fabarta个人专属智能体:三维搜索链+动态大纲重构教材开发范式
  • Omron(欧姆龙)SysmacStudio软件下载,定期更新(最新更新到1.63升级包)
  • npm run 常见脚本
  • BGP协议笔记
  • 【新启航】航空飞机起落架深孔型腔的内轮廓测量方法探究 - 激光频率梳 3D 轮廓检测
  • 2025华数杯数学建模A题【 多孔膜光反射性能的优化与控制】原创论文讲解(含完整python代码)
  • 避免“卡脖子”!如何减少内存I/O延迟对程序的影响?
  • 机器学习——支持向量机(SVM)实战案例
  • 操作系统-实验-进程
  • 机器学习之支持向量机(原理)
  • svm的一些应用
  • 怎么查看Linux I2C总线挂载了那些设备?
  • springboot整合rabbitMQ的示例
  • Elasticsearch:在向量搜索中使用 Direct IO
  • 解码华为云安全“铁三角”:用“分层防御”化解安全挑战
  • 微软披露Exchange Server漏洞:攻击者可静默获取混合部署环境云访问权限
  • 企业AI的双层技术栈架构:融合社区创新与企业级管控的设计蓝图
  • Git 使用场景笔记
  • DuoPlus支持导入文件批量配置云手机参数,还优化了批量操作和搜索功能!
  • 数据结构--哈希表
  • QAGenerationChain从知识库生成大模型应用测试的问题对
  • LeetCode算法日记 - Day 5: 长度最小的子数组、无重复字符的最长子串
  • 【uni-app】解决在 h5 环境下会出现双标题问题
  • 内核的调试和优化
  • Netty-Rest搭建笔记