Can anyone help ccdsap mock question?

can anyone propose a solution for this i have tried backtracking for it but getting tle?
Can anyone give me a better approach?

Basically go from left to right, calculate the number of ways of getting each remainder, starting with ans/dp[0][0]=1;
ans[i][j] represents number of ways to get j mod m using this first i digits(left to right)
also
p2[i] =2^i mod m
After that we know that we can calculate the dp for the next digit by doing this if it is a 1

ans[i+1][(j+p2[l-i-1])%m]+=ans[i][j];

If it is a 0 we do

ans[i+1][j]+=ans[i][j];

for β€˜_’ we do both as it can be either
This solves it in O(nm).
Don’t know why the constraints are so low
https://www.codechef.com/viewsolution/29878828

#include <iostream>
#include <bits/stdc++.h>
#include <cmath>
#include <vector>
#define ll long long int
#define mp make_pair
#define pb push_back
#define vi vector<int>
using namespace std;
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
	int t;
	cin >>t;
	while(t--){
	    int l,m;
	    cin>>l>>m;
	    int p2[l]; //power of 2 mod m
	    p2[0]=1;
	    for(int i=1;i<l;i++){
	        p2[i]=(2*p2[i-1])%m;
	    }
	    ll ans[l+1][m];// number of numbers j mod p possible with the first i digits 
	    for(int i=0;i<=l;i++){
	        for(int j=0;j<m;j++){
	            ans[i][j]=0;
	        }
	    }
	    ans[0][0]=1;
	    for(int i=0;i<l;i++){
	        char a; //because we want one digit at a time
	        cin>>a;
	        if(a=='1'){
	        for(int j=0;j<m;j++){
	            ans[i+1][(j+p2[l-i-1])%m]+=ans[i][j];
	        }
	        }
	        else if(a=='0'){
	            for(int j=0;j<m;j++){
	            ans[i+1][j]+=ans[i][j];
	            }
	        }
	        else{
	            for(int j=0;j<m;j++){
	            ans[i+1][j]+=ans[i][j];
	            ans[i+1][(j+p2[l-i-1])%m]+=ans[i][j];
	            }
	        }
	    }
	    cout<<ans[l][0]<<"\n";
	    
	    
	}
	
}
4 Likes

huh!
when will i be able to think so profoundly!
amazing.Thanks :slight_smile:
:frowning: