Nuclear power plant problem
description
A nuclear power plant has N pits for releasing nuclear material, and the pits are arranged in a straight line. If nuclear material is put in M consecutive pits, an explosion will occur, so nuclear material may not be put in some pits.
Now, please calculate: For a given N and M, find the total number of plans for placing nuclear material that does not explode.
format
Input format
The input file has only one line, two positive integers N and M.
Output format
The output file has only one positive integer, which represents the total number of solutions.
Example 1
Sample input 1
4 3
Sample output 1
13
limit
1s
prompt
All data n<=50, m<=5
Problem solving
Option One
Consider every situation
// dp[i][j] 表示第i个坑已经放置j个连续时的方案数
// 每个坑有放与不放两个选择
// 放: dp[i][j] = dp[i - 1][j - 1]
// 不放(即把当前留为空): dp[i][0] += dp[i - 1][k] (0 <= k < m)
Code
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
typedef long long ll;
const int maxn = 52;
int N, M;
ll ans;
ll dp[maxn][6];
int main() {
cin >> N >> M;
dp[1][1] = 1, dp[1][0] = 1;
for (int i = 2; i <= N; i++)
for (int j = 0; j < M; j++) {
if (j)
dp[i][j] = dp[i - 1][j - 1];
else
for (int k = 0; k < M; k++) dp[i][j] += dp[i - 1][k];
}
for (int j = 0; j < M; j++) ans += dp[N][j];
cout << ans << endl;
system("pause");
return 0;
}
Option II
Discuss ideas in categories, determine the key k value
// dp[i] 表示第i个坑时的方案数
// i = 0时, 没有坑只有一种方案dp[0] = 1
// i < m时, 可以任意放, 每个坑有两种方案, 则 dp[i] = dp[i - 1] * 2;
// i = m时, 除去全部放的方案, 则 dp[i] = dp[i - 1] * 2 - 1;
// i > m时, 要除去更多的方案, 则 dp[i] = dp[i - 1] * 2 - k;
/* 关于k的值 k = dp[i - m - 1]
此时依旧有两种方案放或者不放,总的方案数为DP[i-1]*2,而减去的为连续出现m个的可能情况;
当i > m + 1时可以将连续的m个炸弹看做一个炸弹,但是此时这个炸弹是必须存在的;
所以当i == m+1时方案数为DP[0],(即记录初始状态为)之后的状态类似i<m时。
*/
Code
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
typedef long long ll;
const int maxn = 52;
int N, M;
ll ans;
ll dp[maxn];
int main() {
cin >> N >> M;
dp[0] = 1;
for (int i = 1; i <= N; i++) {
if (i < M)
dp[i] = dp[i - 1] * 2;
else if (i == M)
dp[i] = dp[i - 1] * 2 - 1;
else if (i > M)
dp[i] = dp[i - 1] * 2 - dp[i - M - 1];
}
cout << dp[N] << endl;
system("pause");
return 0;
}