The meaning of the question: n items, order to choose t=a[i] or a[i]-1, that is, s=(s+t), how many times is s in [l,r]?
Simple dp, dp[i][j]: the optimal number of times to select the first i items to j;
dp[i][j]=max(dp[i-1][(j-a[i]+h)%h],dp[i-1][(j-a[i]+1)%h]);
In judging whether j is in the interval [l,r], if it is in dp[i][j]++;
See the code for details:
#include <bits/stdc++.h>
using namespace std;
const int maxn=2e3+3;
int n,h,l,r;
int a[2003];
int dp[maxn][maxn];
int main() {
scanf("%d%d%d%d",&n,&h,&l,&r);
for(int i=1;i<=n;i++){
scanf("%d",a+i);
}
//记得初始化,第i个选择只能由第i-1个选择转移过来
memset(dp,0xcf,sizeof(dp));
dp[0][0]=0;
for(int i=1;i<=n;i++){
for(int j=0;j<h;j++){
int x=(j-a[i]+h)%h;
int y=(j-a[i]+1+h)%h;
dp[i][j]=max(dp[i-1][x],dp[i-1][y]);
if(l<=j&&j<=r) dp[i][j]++;
}
}
int ans=0;
for(int i=0;i<h;i++) ans=max(ans,dp[n][i]);
cout<<ans<<endl;
return 0;
}