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 ≤
1 ≤ m ≤ 100
0 ≤ xi ≤ m
输出
Print one integer: the number of arrays modulo .
样例输入
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;
}