您的位置:首页 > 其它

XTU 1233 n个硬币连续m个正面个数(dp)

2015-06-14 21:46 399 查看
题面:

Coins

Problem Description:

Duoxida buys a bottle of MaiDong from a vending machine and the machine give her n coins back. She places them in a line randomly showing head face or tail face on. And Duoxida wants to know how many situations that m continuous coins head face on among
all possible situations. Two situations are considered different if and only if there is at least one position that the coins' faces are different.

Input

The first line contains a integer T(no more than 20) which represents the number of test cases.

In each test case, a line contains two integers n and m.()

Output

For each test case, output the result modulo in one line.

Sample Input

2

4 2

5 2

Sample Output

8

19

Source

XTU OnlineJudge

题意:

求n个硬币连续m个硬币是正面的情况的个数。

解析:

dp[ i ] [ 1 ] 表示当前 i 个硬币 符合 m 个硬币正面的情况数。

dp[ i ] [ 0 ] 表示当前 i 个硬币 不符合m个硬币正面朝上的情况数。

状态转移方程:

dp[ i ] [ 1 ] = dp[ i - 1 ] [ 1 ] * 2 + dp [ i - 1 - m ] [ 0 ];

dp[ i ] [ 0 ] = (2 ^ i - dp[ i ] [ 1 ] + mod ) % mod;

解释:

i 长度符合m个正面朝上的个数 = i - 1长度正面朝上 * 2(可以随便加正反面硬币) + i - 1 - m 长度下不能的情况(连续加m个正面)。

i 长度不符合m个正面朝上 = 2^i次方 - 符合 + mod(没有这个wa, 因为出现了负数) 最后 % mod。

初始条件:

dp[ m ] [ 1 ] = 1。

dp[ m ] [ 0 ] = 2 ^ m - dp[ m ] [ 1 ] 。

代码:

#include <iostream>
#include <cstdio>
using namespace std;

#define LL long long
#define lson lo, mi, rt << 1
#define rson mi + 1, hi, rt << 1 | 1

const int maxn = 1e6 + 10;
const int mod = 1e9 + 7;
LL dp[maxn][2];
LL two[maxn];

void init()
{
LL s = 1;
for (int i = 0; i < maxn; i++)
{
two[i] = s % mod;
s = (s << 1) % mod;
}
}

int main()
{
#ifdef LOCAL
//freopen("in.txt", "r", stdin);
#endif // LOCAL
init();
int ncase;
scanf("%d", &ncase);
while (ncase--)
{
int n, m;
scanf("%d%d", &n, &m);
dp[m][1] = 1;
dp[m][0] = two[m] - dp[m][1];
for (int i = 0; i < m; i++)
dp[i][0] = two[i];
for (int i = m + 1; i <= n; i++)
{
dp[i][1] = ((dp[i - 1][1] << 1) % mod + dp[i - 1 - m][0] % mod) % mod;
dp[i][0] = (two[i] - dp[i][1] + mod) % mod;
}
printf("%lld\n", dp
[1] % mod);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: