公牛和母牛 (Standard IO)

Description

  FJ想N头牛(公牛或母牛)排成一排接受胡总的检阅,经研究发现公牛特别好斗,如果两头公牛离得太近就会发生冲突,通过观察两头公牛之间至少要有K(0<=K<=N)头母牛才能避免冲突。
  FJ想请你帮忙计算一共有多少种放置方法,注意所有的公牛被认为是一样的,母牛也是,所以两种放置方法被认为不同当且仅当某些位置牛的种类不同。

Input

  第一行:两个空格隔开的整数N(N<=100000)和K。

Output

  输出一个整数表示方法总数,答案可能很大,所以只需输出mod 5,000,011的值即可。

题解

by Neal Wu
The solution to this problem uses a technique called dynamic programming, also known as DP. Let fn be the number of ways we can have a sequence of n animals so that no two bulls have fewer than K cows between them. We first note that f0 = 1. We then try to find a recurrence to compute fn in general by considering two cases for the first animal in the sequence:
• If it is a cow, then we have no restrictions on how we may place the other n - 1 animals, so we have fn - 1 ways to finish the sequence.
• If it is a bull, then the next K animals must be cows, but after that we have no more restrictions, so the number of ways to finish the sequence is fn - K - 1. (Note that when n < 0, we define fn to be 1.)
Thus, combining our two cases together, we have the recurrence fn = fn - 1 + fn - K - 1.

代码

const
  mo=5000011;
var
  n,m,i:longint;
  f:array [0..100001] of longint;
begin
  readln(n,m);
  for i:=0 to n do
    if i<=m then f[i]:=i+1
            else f[i]:=(f[i-1]+f[i-m-1]) mod mo;
  write(f[n]);
end.

原文地址:https://www.cnblogs.com/zyx-crying/p/9319556.html