Test instructions
Find the number of binary numbers with an equal length of n, 0, and 1 numbers, no leading 0, and a multiple of K.
Analysis:
This problem should be done with dynamic planning.
Set DP (zeros, ones, MoD) to have zeros 0,ones 1, divided by the remainder of K is the number of binary numbers of the MoD, then the state transition equation is:
DP (zeros + 1, ones, (mod>>1)% k) + = DP (zeros, ones, MoD)
DP (zeros, ones + 1, ((mod>>1) +1)% k) + = DP (zeros, ones, MoD)
Using the memory search and recursive way to write again, recursion than the memory of the search faster than half the time.
1#include <cstdio>2#include <cstring>3 4 intN, K;5 Long Longd[ *][ *][ the];6 7 Long LongdpintZeros,intOnesintMoD)8 {9 if(zeros + ones > N | | zeros > n/2|| Ones > n/2)return 0;Ten if(D[zeros][ones][mod]! =-1)returnD[zeros][ones][mod]; One returnD[ZEROS][ONES][MOD] = DP (zeros+1, Ones, (mod<<1)%k) + DP (Zeros, ones+1, (((mod<<1)%k) +1)%k); A } - - intMain () the { - //freopen ("In.txt", "R", stdin); - - intT; +scanf"%d", &T); - for(intKase =1; Kase <= T; ++Kase) + { Ascanf"%d%d", &n, &k); at - if(n%2==1|| K = =0) {printf ("Case %d:0\n", Kase);Continue; } - -memset (D,-1,sizeof(d)); -d[n/2][n/2][0] =1; -printf"Case %d:%lld\n", Kase, DP (0,1,1)); in - } to + return 0; -}
Memory Search
1#include <cstdio>2#include <cstring>3 4 intN, K;5 Long Longdp[ *][ *][ the];6 7 intMain ()8 {9 //freopen ("In.txt", "R", stdin);Ten One intT; Ascanf"%d", &T); - for(intKase =1; Kase <= T; ++Kase) - { thescanf"%d%d", &n, &k); - - if(n%2==1|| K = =0) {printf ("Case %d:0\n", Kase);Continue; } - +N/=2; -Memset (DP,0,sizeof(DP)); + Adp[0][1][1%K] =1; at for(inti =0; I <= N; i++) - for(intj =0; J <= N; J + +) - for(intm =0; M < K; m++) - { -dp[i+1][j][(m<<1)%k] + =Dp[i][j][m]; -dp[i][j+1[(m<<1)+1)%k] + =Dp[i][j][m]; in } - toprintf"Case %d:%lld\n", Kase, dp[n][n][0]); + - } the * return 0; $}
Recursive
UVa 12063 (DP) Zeros and Ones