CSES-Solutions | Dynamic Programming
Problem 1 Array Description
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.
Input
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.
Output
Print one integer: the number of arrays modulo 109+7.
Solution CODE:
#include
using namespace std;
typedef long long ll;
const int maxN = 1e5;
const int maxM = 100;
const ll MOD = 1e9+7;
int N, M, x[maxN+1];
ll ans, dp[maxN+1][maxM+1];
int main(){
scanf("%d %d", &N, &M);
for(int i = 1; i <= N; i++)
scanf("%d", &x[i]);
if(x[1])
dp[1][x[1]] = 1;
else
for(int i = 1; i <= M; i++)
dp[1][i] = 1;
for(int i = 2; i <= N; i++){
for(int j = 1; j <= M; j++){
dp[i][j] = dp[i-1][j];
if(j != 1) dp[i][j] += dp[i-1][j-1];
if(j != M) dp[i][j] += dp[i-1][j+1];
dp[i][j] %= MOD;
}
if(x[i])
for(int j = 0; j <= M; j++)
if(j != x[i])
dp[i][j] = 0;
}
for(int i= 1; i <= M; i++)
ans = (ans + dp[N][i]) % MOD;
printf("%lld\n", ans);
}