forked from codersinghal/Competitive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdigitdp.cpp
More file actions
110 lines (81 loc) · 1.77 KB
/
digitdp.cpp
File metadata and controls
110 lines (81 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//
// main.cpp
// digitdp1
//
// Created by Vatsal Chanana on 11/06/15.
// Copyright (c) 2015 VC. All rights reserved.
//
#include<bits/stdc++.h>
using namespace std;
string tostring(long long n)
{
string s;
while(n!=0)
{
s+=(n%10)+'0';
n/=10;
}
reverse(s.begin(), s.end());
return s;
}
long long dp[12][2][83]; //dp[index][smaller][remainder]
//For integers, the sum of digits can't be greater than 82
long long k;
string s;
long long dp_solve(string & s,int index,bool smaller,int mod1)
{
if(index==s.length())
{
if(mod1==0)
{
return 1;
}
return 0;
}
if(dp[index][smaller][mod1]!=-1)
{
return dp[index][smaller][mod1];
}
else
{
int limit=9;
if(smaller)
{
limit=s[index]-'0';
}
long long init_count=0;
for(int i=0;i<=limit;i++)
{
bool ns;
if(i<s[index]-'0')
{
ns=0;
}
else
{
ns=smaller;
}
init_count+=dp_solve(s, index+1, ns,(mod1+i)%k);
}
dp[index][smaller][mod1]=init_count;
return init_count;
}
}
int main()
{
int a,b; //Find numbers between A and B whose sum of digits is divisible by K
cin>>a>>b>>k;
//If A and B are ints, then the sum of the digits can't be greater than 82
if(k>82)
{
cout<<"0\n";
}
string s=tostring(a-1);
string s2=tostring(b);
memset(dp,-1,sizeof(dp));
long long a1=dp_solve(s,0,1,0); //Solving for a-1
memset(dp,-1,sizeof(dp));
long long a2=dp_solve(s2, 0, 1, 0); //Solving for b
cout<<a2-a1<<endl;
return 0;
}