(2016 Multi-University Training Contest 5)
题意:
求区间L至R(闭区间),任意相邻k位(如果位数不足k,就是全部的数位)没有两两相同的数位的数的个数。
思路:
需要保存当前位前四位的数值,进行数位DP,不保存的话无法进行记忆化保存,因为都是先进行pos低位的记忆化保存,那么限制条件是什么?(!limit && !lead)前面所有位不是最高位并且不是前导零的情况?这样是不行的,假如pos共5位,K为2,则当对pos=3位进行记忆化保存之后,轮到pos=4的某个时刻,直接读取dp值是不对的,因为假设当前值为2,那么下一位保存的仅仅时pos=4位为0或者1或者前导零的情况,所以pos=3位的dp值包括其取2的情况,那么会出错的,言语无法表达出那个具体意思,自己想吧~~所以需要对pre进行存储,然后建立一个五维的dp。
代码1:
#include <bits/stdc++.h>
#define LL long long
using namespace std;
LL dp[18][11][11][11][11], L, R;
int num[18], K;
LL dfs(int pos, int limit, int lead, int pre1, int pre2, int pre3, int pre4)
{
if(pos == -1) return 1;
if(!limit && !lead && pos+1 >= K && dp[pos][pre1][pre2][pre3][pre4] != -1)
return dp[pos][pre1][pre2][pre3][pre4];
int up = limit? num[pos]: 9;
LL tmp = 0;
for(int i = 0, j; i <= up; ++i)
{
if(lead && i == 0)
{
tmp += dfs(pos-1, limit&&i==num[pos], 1, 10, 10, 10, 10);
continue;
}
if(pre1!=i && pre2!=i && pre3!=i && pre4!=i)
{
tmp += dfs(pos-1, limit&&i==num[pos], lead&&i==0, K>1?i:10, K>2?pre1:10, K>3?pre2:10, K>4?pre3:10);
}
}
if(!limit && !lead && pos+1 >= K) dp[pos][pre1][pre2][pre3][pre4] = tmp;
return tmp;
}
LL solve(LL x)
{
int pos = 0;
while(x)
{
num[pos++] = x%10;
x /= 10;
}
return dfs(pos-1, 1, 1, 10, 10, 10, 10);
}
int main()
{
while(~scanf("%lld %lld %d", &L, &R, &K))
{
memset(dp, -1, sizeof dp);
printf("%lld\n", solve(R)-solve(L-1));
}
return 0;
}
上述!limit和!lead是我们最常加上的,然后加一个 pos+1 >= K 是为了仅当后面位数大于等于K个才进行记忆化,但效率很低,时间达到 2402ms。
代码2:
#include <bits/stdc++.h>
#define LL long long
using namespace std;
LL dp[18][11][11][11][11], L, R;
int num[18], K;
LL dfs(int pos, int limit, int lead, int pre1, int pre2, int pre3, int pre4)
{
if(pos == -1) return 1;
if(!limit && dp[pos][pre1][pre2][pre3][pre4] != -1)
return dp[pos][pre1][pre2][pre3][pre4];
int up = limit? num[pos]: 9;
LL tmp = 0;
for(int i = 0, j; i <= up; ++i)
{
if(lead && i == 0)
{
tmp += dfs(pos-1, limit&&i==num[pos], 1, 10, 10, 10, 10);
continue;
}
if(pre1!=i && pre2!=i && pre3!=i && pre4!=i)
{
tmp += dfs(pos-1, limit&&i==num[pos], lead&&i==0, K>1?i:10, K>2?pre1:10, K>3?pre2:10, K>4?pre3:10);
}
}
if(!limit) dp[pos][pre1][pre2][pre3][pre4] = tmp;
return tmp;
}
LL solve(LL x)
{
int pos = 0;
while(x)
{
num[pos++] = x%10;
x /= 10;
}
return dfs(pos-1, 1, 1, 10, 10, 10, 10);
}
int main()
{
while(~scanf("%lld %lld %d", &L, &R, &K))
{
memset(dp, -1, sizeof dp);
printf("%lld\n", solve(R)-solve(L-1));
}
return 0;
}
再经分析:发现lead表示前导零其实多此一举,因为我们开的五维数组已经将前面是不是前导零的给表示出来了,即pre1的值即其之后都是10,然后又发现 pos+1 >= K 的判断也是不需要的,因为此时已经可以通过这四维的pre来进行限制了,比如个位数会记忆化入dp[0][10][10][10][10]当中,而当较大的pos位来进行尝试记忆化读取时,则不会直接返回dp值,因为较大的pos传下来就肯定会有相应的pre值,所以通过这个限制便不会出错了。
效率提高若干倍,耗时 46ms。
继续加油~