牛客 数位dp

链接:https://www.nowcoder.com/acm/contest/163/J
来源:牛客网

#include
#include
#include
#include
#include
#include
#include
#include
#define mem(a,x) memset(a,x,sizeof(a))
#define s1(x) scanf("%d",&x)
#define s2(x,y) scanf("%d%d",&x,&y)
#define s3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define s4(x,y,z,k) scanf("%d%d%d%d",&x,&y,&z,&k)
#define ff(a,n) for(int i = 0 ; i < n; i++) scanf("%d",a+i)
#define tp(x) printf("x = %d\n",x)
#define ansp(x) printf("%d\n",x)
//inline ll ask(int x){ll res=0;while(x)res+=c[x],x-=x&(-x);return res;}
//inline void add(int x,int d){while(x<=n)c[x]+=d,x+=x&(-x);}
#define ls 2*rt
#define rs 2*rt+1
#define lson ls,L,mid
#define rson rs,mid+1,R
#define ll long long
#define LL long long
using namespace std;
typedef pair pii;
const ll inf = 0x3f3f3f3f;
//const int mod = 2520;

int dig[14];
ll dp[14][110][110][110];  //位数 位数之和 之和取余结果 余数 

 
 ll dfs(int pos, int presum, int num,int mod, bool limit){
 	if(pos == -1){
 		if(presum == mod&&!num)
 			return 1;
		return 0;
	 }
 		           
 	if(!limit && dp[pos][presum][num][mod] != -1)
 		return dp[pos][presum][num][mod];
 	
	 int n = limit?dig[pos]:9;
 	ll ans = 0;
 	for(int i = 0; i <= n; i++){
		ans += dfs(pos-1,presum+i,(num*10+i)%mod,mod,limit&& i == n); 
	 }
	 if(!limit)
	 		dp[pos][presum][num][mod] = ans;
	 return ans;
 }
 

 ll calc( ll x){
 	int pos = 0;
 	while(x){
 		dig[pos++] = x%10;
		x /= 10;	
	}
	ll ans = 0;
	for(int i = 1; i <= 108; i++)
		ans += dfs(pos-1,0,0,i,1);
	return ans;
 }
 
int main(){
	//	freopen("F:\\in.txt","r",stdin);
	int co = 0;

	mem(dp,-1);
	int T=10;	scanf("%d",&T);
	ll n;
	for(int ca =1; ca <= T;  ca++){
		
		scanf("%lld",&n);
		printf("Case %d: %lld\n",ca,calc(n));
	
	}
	
	return 0;
}

 

你可能感兴趣的:(数位dp)