Adjacent Bit Counts
For a string of n bits x1, x2, x3,…, xn, the adjacent bit count of the string (AdjBC(x)) is given by
x1 ∗ x2 + x2 ∗ x3 + x3 ∗ x4 + . . . + xn−1 ∗ xn
which counts the number of times a 1 bit is adjacent to another 1 bit. For example:
AdjBC(011101101) = 3
AdjBC(111101101) = 4
AdjBC(010101010) = 0
Write a program which takes as input integers n and k and returns the number of bit strings x of nbits (out of 2n) that satisfy AdjBC(x) = k. For example, for 5 bit strings, there are 6 ways of getting
AdjBC(x) = 2:
11100, 01110, 00111, 10111, 11101, 11011
Input
The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that
follow. Each data set is a single line that contains the data set number, followed by a space, followed by
a decimal integer giving the number (n) of bits in the bit strings, followed by a single space, followed by
a decimal integer (k) giving the desired adjacent bit count. The number of bits (n) will not be greater
than 100 and the parameters n and k will be chosen so that the result will fit in a signed 32-bit integer.
Output
For each data set there is one line of output. It contains the data set number followed by a single space,
followed by the number of n-bit strings with adjacent bit count equal to k.
Sample Input
10
1 5 2
2 20 8
3 30 17
4 40 24
5 50 37
6 60 52
7 70 59
8 80 73
9 90 84
10 100 90
Sample Output
1 6
2 63426
3 1861225
4 168212501
5 44874764
6 160916
7 22937308
8 99167
9 15476
10 23076518
題意
給你一個長度為n的01字串s,問你按照題目所給方式計算AdjBC(s),有多少種長度為n的01字串的AdjBC值為k。
AdjBC(s) =
*
+
*
+
*
+
+
*
思路
找規律的題,可以用動態規劃來搞一搞。
觀察發現:
- 長度為n+1的字串由長度為n的字串通過在最前面增加一個1或0得到。
- 在一個串前加一個0不改變串的AdjBC。
- 在一個串前加一個1取決於原串最前面的字元,若原串最前面是1,新串的AdjBC值等於原串AdjBC值+1, 否則等於原串AdjBC值。
設:dp[i][j][k]
- i 代表長度為i的字串
- j 代表該串的AdjBC值
- k 代表該串最前面的字元是1還是0
根據規律有動態轉移方程:
dp[i][j][0] = dp[i - 1][j][0] + dp[i - 1][j][1]
dp[i][j][1] = dp[i - 1][j - 1][1] + dp[i - 1][j][0]
特殊的:
當 j == 0 時,dp[i][j][1] = dp[i - 1][j][0]
Code
#include <bits/stdc++.h>
#define N 110
#define INF 0x3f3f3f3f
using namespace std;
int dp[N][N][2];
void Solve()
{
dp[1][0][0]=1;
dp[1][0][1]=1;
for(int i=2; i<=100; i++)
{
for(int j=0; j<i; j++)
{
if(j==0)
{
dp[i][j][1]=dp[i-1][j][0];
dp[i][j][0]=dp[i-1][j][0]+dp[i-1][j][1];
}
else
{
dp[i][j][0]=dp[i-1][j][0]+dp[i-1][j][1];
dp[i][j][1]=dp[i-1][j-1][1]+dp[i-1][j][0];
}
}
}
}
int main()
{
Solve();
int T,z,b,m;
cin>>T;
while(T--)
{
cin>>z>>b>>m;
cout<<z<<" "<<dp[b][m][0]+dp[b][m][1]<<endl;
}
return 0;
}