CodeForces - 1073E :Segment Sum (数位DP)

时间:2023-03-10 00:24:58
CodeForces - 1073E :Segment Sum (数位DP)

You are given two integers l l and r r (l≤r l≤r ). Your task is to calculate the sum of numbers from l l to r r (including l l and r r ) such that each number contains at most k k different digits, and print this sum modulo 998244353 998244353 .

For example, if k=1 k=1 then you have to calculate all numbers from l l to r r such that each number is formed using only one digit. For l=10,r=50 l=10,r=50 the answer is 11+22+33+44=110 11+22+33+44=110 .

Input

The only line of the input contains three integers l l , r r and k k (1≤l≤r<10 18 ,1≤k≤10 1≤l≤r<1018,1≤k≤10 ) — the borders of the segment and the maximum number of different digits.

Output

Print one integer — the sum of numbers from l l to r r such that each number contains at most k k different digits, modulo 998244353 998244353 .

Examples

Input
10 50 2
Output
1230
Input
1 2345 10
Output
2750685
Input
101 154 2
Output
2189

题意:求区间[L,R]的满足digit种类不超过K的数字之和。

思路:与常规我数位DP不一样的是,这里求是不是个数,而是这些书之和。所以我们要记录一个二元组(x,y)分别表示(子树之和,子树叶子个数)。

(数位DP其实就是一棵树,子树相同的时候可以直接调用答案)

那么当前节点为根的树的信息=(所有子树的和+当前位*叶子个数,所有叶子个数之和)。

#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define ll long long
#define pii pair<int,int>
#define mp make_pair
using namespace std;
const int Mod=;
pii dp[][<<],O=mp(,);
int v[],num[<<],K,q[],tot;
pii dfs(int pos,int st,int lim)
{
if(!lim&&dp[pos][st]!=O) return dp[pos][st];
if(pos==) return mp(,);
int up=; pii res=O,tmp; if(lim) up=q[pos-];
rep(i,,up){
if(num[st|(<<i)]<=K){
tmp=dfs(pos-,st|(<<i),lim&&i==up);
(res.second+=tmp.second)%=Mod;
(res.first+=tmp.first)%=Mod;
(res.first+=(ll)v[pos-]*i%Mod*tmp.second%Mod)%=Mod;
}
}
return dp[pos][st]=res;
}
int cal(ll x)
{
if(x==) return ;
tot=; int ans=;
while(x) q[++tot]=x%,x/=;
memset(dp,,sizeof(dp));
rep(i,,tot){
ll up=; if(i==tot) up=q[tot];
rep(j,,up){
pii tmp=dfs(i,<<j,(i==tot)&&(j==q[tot]));
(ans+=(ll)v[i]*j%Mod*tmp.second%Mod)%=Mod;
(ans+=tmp.first)%=Mod;
}
}
return ans;
}
int main()
{
rep(i,,<<) num[i]=num[i>>]+(i&);
v[]=; rep(i,,) v[i]=(ll)v[i-]*%Mod;
ll L,R; scanf("%lld%lld%d",&L,&R,&K);
printf("%d\n",((cal(R)-cal(L-))%Mod+Mod)%Mod);
return ;
}