There are r red and g green blocks for construction of the red-green tower. Red-green tower can be built following next rules:
Red-green tower is consisting of some number of levels;
Let the red-green tower consist of n levels, then the first level of this tower should consist of n blocks, second level — of n?-?1 blocks, the third one — of n?-?2 blocks, and so on — the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one;
Each level of the red-green tower should contain blocks of the same color.
Let h be the maximum possible number of levels of red-green tower, that can be built out of r red and g green blocks meeting the rules above. The task is to determine how many different red-green towers having h levels can be built out of the available blocks.
Two red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower.
You are to write a program that will find the number of different red-green towers of height h modulo 109?+?7.
Input
The only line of input contains two integers r and g, separated by a single space — the number of available red and green blocks respectively (0?≤?r,?g?≤?2·105, r?+?g?≥?1).
Output
Output the only integer — the number of different possible red-green towers of height h modulo 109?+?7.
Sample test(s)
Input
4 6
Output
2
Input
9 7
Output
6
Input
1 1
Output
2
Note
The image in the problem statement shows all possible red-green towers for the first sample.
用r块红色、g块绿色的方块,搭成一个h层(尽可能高)的塔,第i层有i个相同颜色的方块。
问所有可行的方案有多少。
动态规划
dp(h, r) 表示到h层,已用r块红色的方案数
绿色个数可以通过h,r确定。
dp(h, r) = dp(h-1, r-h) + dp(h-1, r)
明显可以滚动压缩,dp只与之前一次相关,r反向循环避免引用修改过的数据。
dp[r] += dp[r-h];
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int MAXN = 200010;
const int MOD = 1e9 + 7;
int dp[MAXN], R, G, H, ans;
void init() {
memset(dp, 0, sizeof(dp));
dp[0] = 1;
ans = 0;
}
void solve() {
int h;
for (h = 1; h*(h+1) <= 2*(R+G); h++) {
for (int r = min(h*(h+1)/2, R); r >= h; r--) {
dp[r] = (dp[r] + dp[r-h]) % MOD;
}
}
H = h - 1;
for (int r = max(0, H*(H+1)/2-G); r <= min(H*(H+1)/2, R); r++) {
ans = (ans + dp[r]) % MOD;
}
printf("%d\n", ans);
}
int main() {
while (~scanf("%d%d", &R, &G)) {
init();
solve();
}
return 0;
}
Codeforces 478D Red-Green Towers (DP)
原文地址:http://blog.csdn.net/wujysh/article/details/44153133