ACWing 1307. Stall and Bull (combination number, DP, prefix sum)

1307. Stall and Cow

Idea One

  • f [ i ] f[i] f [ i ] means there isiiThe number of plans for i cows and the last cow must be a bull.
  • f [ i ] = ∑ 0 i − k − 1 f [ i ] f[i] =\sum_{0}^{i-k-1} f[i] f[i]=0ik1f[i] ( s [ i − k , i − 1 ] ) (s[i-k,i-1]) (s[ik,i1 ] ) Only cows are allowed.
  • The final answer: ∑ 0 nf [i] \sum_{0}^{n}f[i]0nf [ i ] , do things in categories, the principle of addition.
#include <stdio.h>
using namespace std;

const int mod = 5000011,size = 1e5+10;
int n,k,f[size] = {
    
    1},s[size] = {
    
    1};

int main(){
    
    
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++){
    
    
        f[i] = i-k-1>=0?s[i-k-1]:f[0];
        s[i] = (s[i-1]+f[i])%mod;
    }
    printf("%d\n",s[n]);
    return 0;
}

Idea two

  • Use f [i] f[i] directlyf [ i ] means there isiiNumber of plans for i cattle
    • If iii cow is a cow, theni − 1 i-1i1 head can be placed casually according to the requirements of the subject.
    • If iii cow is a bull,s [i − k] s[ik]s[ik]~ s [ i − 1 ] s[i-1] s[i1 ] None can be bulls, only cows.
      So at this timei − k − 1 ik-1ik1 cow is placed randomly according to the requirements of the subject.
      f [i] = f [i − 1] + f [i − k − 1] f[i]=f[i-1]+f[ik-1]f[i]=f[i1]+f[ik1]
  • The answer is f [n] f[n]f[n]
#include <stdio.h>
using namespace std;

const int mod = 5000011,size = 1e5+10;
int n,k,f[size] = {
    
    1};

int main(){
    
    
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++){
    
    
        f[i] = f[i-1];
        if(i-k-1>=0) f[i] = (f[i]+f[i-k-1])%mod;
        else f[i] = (f[i]+1)%mod;
    }
    printf("%d\n",f[n]);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44846324/article/details/108574520