Adjacent Bit Counts
-
描述
-
For a string of n bits x1, x2, x3, …, xn, the adjacent bit count of the string is given by fun(x) = x1*x2 + x2*x3 + x3*x 4 + … + xn-1*x n
which counts the number of times a 1 bit is adjacent to another 1 bit. For example:Fun(011101101) = 3
Fun(111101101) = 4
Fun (010101010) = 0
Write a program which takes as input integers n and p and returns the number of bit strings x of n bits (out of 2ⁿ) that satisfy Fun(x) = p.
For example, for 5 bit strings, there are 6 ways of getting fun(x) = 2:
11100, 01110, 00111, 10111, 11101, 11011
-
输入
- On the first line of the input is a single positive integer k, telling the number of test cases to follow. 1 ≤ k ≤ 10 Each case is a single line that contains a decimal integer giving the number (n) of bits in the bit strings, followed by a single space, followed by a decimal integer (p) giving the desired adjacent bit count. 1 ≤ n , p ≤ 100 输出
- For each test case, output a line with the number of n-bit strings with adjacent bit count equal to p. 样例输入
-
25 220 8
样例输出
-
663426
分析:
意思的大意是给你一个只含01的字符串,他的值就是任意两个相邻0或1的积的和;
给你个n和m,n为串的长度,m为串的值,问符合条件的串有多少种;
定义数组f[101][101][2];其中f[i][j][0]代表第j位是0的时候长度为j的串组成值为i的串的种数,f[i][j][1]代表第j位是1的时候长度为j的串组成值为i的串的种数,
容易看出f[i][j][0]=f[i][j-1][0]+f[i][j-1][1]; f[i][j][1]=f[i-1][j-1][1]+f[i][j-1][0];
所以此题就出来了,初始化先把f的值全部赋成0.然后f[0][1][0]=f[0][1][1]=0;然后先求出所有f[0][i]的值;
还有就是f[i][i+1][1]=1;
#include<stdio.h>
int main()
{
int m,i,j,a,b,dp[101][101][2];
dp[1][0][1]=dp[2][0][1]=1;//因为是相乘的积的和,所以只能是1
for(i=3;i<101;i++)
dp[i][0][1]=dp[i-1][0][1]+dp[i-2][0][1];//因为新加的是1,所以前面符合之和
for(i=1;i<101;i++)
for(j=1;j<101;j++)//后面依次类推,得到结果
{
dp[i][j][0]=dp[i-1][j][0]+dp[i-1][j][1];
dp[i][j][1]=dp[i-1][j][0]+dp[i-1][j-1][1];
}
scanf("%d",&m);
while(m--)
{
scanf("%d%d",&a,&b);
printf("%d\n",dp[a][b][0]+dp[a][b][1]);
}
return 0;
}