FZU 2109 Mountain Number ---數位dp
One integer number x is called "Mountain Number" if:
(1) x>0 and x is an integer;
(2) Assume x=a[0]a[1]...a[len-2]a[len-1](0≤a[i]≤9, a[0] is positive). Any a[2i+1] is larger or equal to a[2i] and a[2i+2](if exists).
For example, 111, 132, 893, 7 are "Mountain Number" while 123, 10, 76889 are not "Mountain Number".
Now you are given L and R, how many "Mountain Number" can be found between L and R (inclusive) ?
Input
The first line of the input contains an integer T (T≤100), indicating the number of test cases.
Then T cases, for any case, only two integers L and R (1≤L≤R≤1,000,000,000).
Output
For each test case, output the number of "Mountain Number" between L and R in a single line.
Sample Input
3 1 10 1 100 1 1000
Sample Output
9 54 384
題意:
如果一個>0的整數x,滿足a[2*i+1] >= a[2*i]和a[2*i+2],則這個數為Mountain Number。
給出L, R,求區間[L, R]有多少個Mountain Number。
思路:
數位DP,判斷當前是偶數位還是奇數位(從0開始),
如果是偶數位,那麼它要比前一個數的值小,
如果是奇數位,那麼它要比前一個數的值大。
不明白為什麼開long long 就答案錯誤
#include<iostream> #include<cstring> #include<cstdio> using namespace std; typedef long long ll; int a[30]; int dp[30][15][15]; int dfs(int pos,int pre,int sta,bool limit){ if(pos<0){ return 1; } if(!limit&&dp[pos][pre][sta]!=-1) return dp[pos][pre][sta]; int up=limit?a[pos]:9; int tmp=0; for(int i=0;i<=up;i++) { if(sta && i<=pre) tmp+=dfs(pos-1,i,0,limit && i==up); if(!sta && i>=pre) tmp+=dfs(pos-1,i,1,limit && i==up); } if(!limit) dp[pos][pre][sta]=tmp; return tmp; } int solve(int x) { memset(a,0,sizeof(a)); int pos=0; while(x) { a[pos++]=x%10; x/=10; } return dfs(pos-1,9,1,1); } int main() { memset(dp,-1,sizeof(dp)); int n,m; int T; cin>>T; while(T--) { scanf("%d%d",&n,&m); printf("%d\n",solve(m)-solve(n-1)); } return 0; }