【HDOJ6148】Valley Numer(数位DP)

题意:

 1≤T≤200

● 1≤length(N)≤100

思路:

设f[i,j,k,l]为第i位为j,前i位是否贴上限(0/1),递减或递增(0/1)方案数

g[i,j,k]为不到n位,第i位为j,递减或递增方案数

 1 const mo=1000000007;
 2 var f:array[0..105,0..10,0..2,0..2]of longint;
 3     g:array[0..105,0..10,0..2]of longint;
 4     a:array[1..105]of longint;
 5     v,n,i,j,k,l,jj,kk,ans,cas,ll:longint;
 6     ch:string;
 7 
 8 begin
 9 
10  readln(cas);
11  for v:=1 to cas do
12  begin
13   readln(ch);
14   n:=length(ch);
15   for i:=1 to n do a[i]:=0;
16   for i:=1 to n do a[i]:=ord(ch[i])-ord('0');
17   for i:=1 to n do
18    for j:=0 to 9 do
19     for k:=0 to 1 do
20      for l:=0 to 1 do f[i,j,k,l]:=0;
21   for i:=1 to a[1]-1 do f[1,i,0,0]:=1;
22   f[1,a[1],1,0]:=1;
23   for i:=2 to n do
24    for j:=0 to 9 do
25     for k:=0 to 1 do
26      for l:=0 to 1 do
27       for jj:=0 to 9 do
28       begin
29        if k=0 then kk:=0;
30        if (k=1)and(jj<a[i]) then kk:=0;
31        if (k=1)and(jj=a[i]) then kk:=1;
32        if (k=1)and(jj>a[i]) then break;
33        for ll:=l to 1 do
34        begin
35         if (ll=0)and(j<jj) then continue;
36         if (ll=1)and(j>jj) then continue;
37         if (ll<>l)and(j=jj) then continue;
38         f[i,jj,kk,ll]:=(f[i,jj,kk,ll]+f[i-1,j,k,l]) mod mo;
39        end;
40       end;
41   for i:=1 to n-1 do
42    for j:=0 to 9 do
43     for k:=0 to 1 do g[i,j,k]:=0;
44   for i:=1 to 9 do g[1,i,0]:=1;
45   for i:=2 to n-1 do
46     for j:=0 to 9 do
47      for k:=0 to 1 do
48       for jj:=0 to 9 do
49        for kk:=k to 1 do
50        begin
51         if (kk=0)and(j<jj) then continue;
52         if (kk=1)and(j>jj) then continue;
53         if (k<>kk)and(j=jj) then continue;
54         g[i,jj,kk]:=(g[i,jj,kk]+g[i-1,j,k]) mod mo;
55        end;
56   ans:=0;
57   for j:=0 to 9 do
58    for k:=0 to 1 do
59     for l:=0 to 1 do ans:=(ans+f[n,j,k,l]) mod mo;
60   for i:=1 to n-1 do
61    for j:=0 to 9 do
62     for k:=0 to 1 do ans:=(ans+g[i,j,k]) mod mo;
63   writeln(ans);
64  end;
65 
66 end.
原文地址:https://www.cnblogs.com/myx12345/p/7413582.html