### algoskipper's blog

By algoskipper, history, 3 weeks ago,

Question from algozenith mocks Microsoft coding test 2 — question 1 This question is asked un Microsoft online assessment which is present in various sites but none of them have provided correct solutions. One can think of bfs but it will give TLE as many steps are repeated a lot of time. So talking about dp optimization. 2D dp where dp[i][j] will give total number of ships when start with value j and total layers are i including current layer. Base case would be for every i dp[i][0]=i and for every j dp[1][j]=1. dp[i][j]= (summation dp[i-1][j] for every j from 0 to (j*j+1)%m-1 ) But its constantly giving wrong answer. And to make it worse nowhere correct answer is given nor failed test case is shown. i think i have something wrong in my idea can anyone clarify. below is my code.

ll l,m;cin>>l>>m;
vector<vector<ll>>dp(l+2,vector<ll>(m+2,0));
f(m){dp[1][i]=1;}

vector<ll>lp(m+1);lp[0]=1;
for(ll i=1;i<l;i++){lp[i]=lp[i-1]+1;}
for(ll i=0;i<l;i++){dp[i][0]=i;}
for(ll j=2;j<=l;j++){

for(ll i=0;i<m;i++){
if(i==0)continue;
if((i*i+1)%m!=0)dp[j][i]=lp[((i*i+1)%m)-1];
dp[j][i]++;

}
for(ll i=0;i<lp.size();i++){if(i==0)lp[i]=dp[j][i];else lp[i]=lp[i-1]+dp[j][i];}

}
cout<<dp[l][2]%m<<endl;


 » 3 weeks ago, # |   0 here is my accepted solution with dp[i][j] = number of nodes in subtree of i upto level j , base is for for all i dp[i][1]=1 , also use prefix sum to get dp states sum otherwise it will tle code...  ll dp[1005][1005]; void solve(){ ll l,m; cin >> l >> m; vector psum; ll sm = 0; for(ll i = 0 ; i < m ; i++){ dp[i][1]=1; sm = (sm+dp[i][1])%m; psum.push_back(sm); } for(ll j = 2 ; j <= l ; j++){ vector temp; sm=0; for(ll i = 0; i < m; i++){ ll mx = ((i*i)%m+1)%m; ll val = 1; if(mx) val=(val+psum[mx-1])%m; dp[i][j]=val; sm = (sm+val)%m; temp.push_back(sm); } psum=temp; } cout << dp[2][l] << ed; }