Breadtree
Problem Description
Breadtree is a kind of tree that produces bread. At its first year, a breadtree is only a node with a bread of weight 0 on this node which is also called zeronode. Every year after that, the weight of bread on each node of the tree will increase by 1, and another branch with a zeronode will grow at the end of each node. However, there is a limit of branches on each node. That is, when the number of branches of a node reaches the limit, there won’t be any more branches, but the weight of its bread will still increase. What’s more, a breadtree remains unchanged when the total weight of bread is larger than 1234567890.
Input
There are two integers N and K on each line. N is a positive integer fit in signed 32-bit integer. K is a non-negative integer fit in signed 32-bit integer. An N equals to 0 signals the end of input, which should not be processed.
Output
Output the total weight of bread on a breadtree with branches limit K in the N-th year in a line for each case.
Sample Input
10000 0
101 1
10 2
1221 128
0 0
Sample Output
9999
5050
221
2147483647
题意
有一棵树,第一天只有一个空树枝。每新的一天,前一天的每节树枝都会长出一个新的果实和一根新的空的树枝。但一个节点最多长出K条树枝,之后将不再生长树枝(可继续产生果实)。果实如果数量大于1234567890,整棵树就会停止生长,给出k,求第n天树上的果实数量。
题解:
动态规划。
对于k==0,结果为min(1234567890+1, n-1)。
对于k>0,设
d
p
[
i
]
dp[i]
dp[i]代表第i天树上的树枝数量,则有
d
p
[
i
]
=
d
p
[
i
−
1
]
+
d
p
[
i
−
1
]
−
d
p
[
m
a
x
(
0
,
i
−
k
−
1
)
]
dp[i]=dp[i-1]+dp[i-1]-dp[max(0,i-k-1)]
dp[i]=dp[i−1]+dp[i−1]−dp[max(0,i−k−1)]第i天有之前旧的
d
p
[
i
−
1
]
dp[i-1]
dp[i−1]个树枝,同时除了第
i
−
k
−
1
i-k-1
i−k−1天之前的树枝,其余树枝都会产生一个新的树枝。
每天,产生的果实数量为
d
p
[
i
−
1
]
dp[i-1]
dp[i−1],如果生长到第n天或者总的果实数量大于1234567890则停止生长。
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<ctype.h>
#include<cstring>
#include<set>
#include<queue>
#include<stack>
#include<iterator>
#define dbg(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
#define eps 1e-6
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int maxn = 1000100;
const int mod = 20100713;
LL dp[maxn];
int main()
{
LL mx = 1234567890LL, n, k, ans, up;
while(scanf("%lld %lld", &n, &k), n)
{
if(k == 0)printf("%lld\n", min(mx+1, n-1LL));
else{
ans = 0;
dp[1] = 1, dp[0] = 0;
for(int i=2;i<=n;i++)
{
ans = ans+dp[i-1];
if(ans > mx)break;
else
dp[i] = 2*dp[i-1]-dp[max(0LL,i-k-1)];
}
printf("%lld\n", ans);
}
}
return 0;
}