题目链接
思路:用数位dp的思想,如果当前位没有限制了,那么我们可以直接算出答案。
考虑每一位产生的逆序对贡献可以很容易计算出答案。
注意如果要考虑记录相同状态的话,一定不要忘记前导零!!!
细节见代码:
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2e5 + 10;
#define fi first
#define se second
#define pb push_back
#define wzh(x) cerr<<#x<<'='<<x<<endl;
typedef array<int,11> arr;
LL fac[16];
int c[20];
LL so(int pos,int st,arr now,int sum,int lead){
if(!pos)return sum;
arr th;
th[0]=now[0];
for(int i=1;i<10;i++)th[i]=th[i-1]+now[i];
if(!st &&!lead){
LL res=0;
for(int i=1;i<=pos;i++){
for(int j=1;j<10;j++){
res+=fac[pos-1]*th[j-1];
if(pos>=2){
res+=(i-1)*j*fac[pos-2];
}
}
}
vis[now]=res;
return res+fac[pos]*sum;
}
int up=st?c[pos]:9;
LL tmp=0;
for(int i=0;i<=up;i++){
if(!i){
if(!lead){
now[0]++;
tmp+=so(pos-1,st&&i==up,now,sum,0);
now[0]--;
}else{
tmp+=so(pos-1,st&&i==up,now,sum,1);
}
}else{
now[i]++;
tmp+=so(pos-1,st&&i==up,now,sum+th[i-1],0);
now[i]--;
}
}
return tmp;
}
int t,cas;
LL a,b;
LL get(LL x){
int tot=0;
//cout<<x<<' ';
while(x){
c[++tot]=x%10;
x/=10;
}
arr now;
vis.clear();
for(int i=0;i<10;i++)now[i]=0;
LL res=so(tot,1,now,0,1);
return res;
}
int main() {
ios::sync_with_stdio(false);
fac[0]=1;
for(int i=1;i<=15;i++)fac[i]=fac[i-1]*10;
for(cin>>t,cas=1;cas<=t;cas++){
cin>>a>>b;
cout<<"Case "<<cas<<": ";
cout<<get(b)-get(a-1)<<'\n';
}
return 0;
}
/*
5
1 9
1 100
50 60
23 2343
345 99373
*/