LightOj 1021 (Painful Bases)

#lightoj #cp #problem_solving #dp #bitmask_dp

Idea


Bitmask DP

  • Take idea from here
  • Note : Using excess memory will give RTE in this problem . So , allocate memory carefully .
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

/**Which of the favors of your Lord will you deny ?**/

#include<bits/stdc++.h>
using namespace std;

#define LL long long
#define PII pair<int,int>
#define PLL pair<LL,LL>
#define MP make_pair
#define F first
#define S second
#define INF INT_MAX

inline void optimizeIO()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}

const int nmax = 18;
const LL LINF = 1e17;

string to_str(LL x)
{
stringstream ss;
ss<<x;
return ss.str();
}

LL dp[1<<17][20];
int ara[200];

int main()
{
optimizeIO();

int tc;
cin>>tc;

for(int q=1; q<=tc; q++)
{
LL base,M;
cin>>base>>M;
string s;
cin>>s;

int len = s.size();

for(LL i=0; i<len; i++)
{
if(s[i]>='0' && s[i]<='9')
{
ara[i]=s[i]-'0';
}
else
{
ara[i]=s[i]-'A'+10;
}
}

memset(dp,0,sizeof dp);

dp[0][0] = 1;

for(int i=0; i< (1<<len); i++)
for(int k=0; k<len; k++)
if(!(i & (1<<k)))
for(int j=0; j<M; j++)
dp[i | (1<<k)][(j*base+ara[k])%M] += dp[i][j];


LL ans = dp[(1<<len)-1][0];

cout<<"Case "<<q<<": "<<ans<<endl;

}

return 0;
}