USACO Section 2.3 Cow Pedigrees(dp)

Cow Pedigrees

Silviu Ganceanu -- 2003

 

Farmer John is considering purchasing a new herd of cows. In this new herd, each mother cow gives birth to two children. The relationships among the cows can easily be represented by one or more binary trees with a total of N (3 <= N < 200) nodes. The trees have these properties:

  • The degree of each node is 0 or 2. The degree is the count of the node's immediate children.
  • The height of the tree is equal to K (1 < K <100). The height is the number of nodes on the longest path from the root to any leaf; a leaf is a node with no children.

How many different possible pedigree structures are there? A pedigree is different if its tree structure differs from that of another pedigree. Output the remainder when the total number of different possible pedigrees is divided by 9901.

PROGRAM NAME: nocows

INPUT FORMAT

  • Line 1: Two space-separated integers, N and K.

SAMPLE INPUT (file nocows.in)

5 3

OUTPUT FORMAT

  • Line 1: One single integer number representing the number of possible pedigrees MODULO 9901.

SAMPLE OUTPUT (file nocows.out)

2

OUTPUT DETAILS

Two possible pedigrees have 5 nodes and height equal to 3:

           @                   @      
          / \                 / \
         @   @      and      @   @
        / \                     / \
       @   @                   @   @

题意:给你 n 个元素,可以组成多少颗深度为 m 的二叉树,每个结点的度只有 0 或 2 。
分析:d[i][j] 表示 i 个结点构成深度小于等于 j 的种数,于是 d[i][j] = d[k][j-1]*d[i-k-1][j-1] , 1<=k<=i-2; 初始条件d[1][k]=1;由于结果恰好是 m 层,于是ans=d[n][m]-d[n][m-1]; ans=(ans%MOD+MOD)%MOD
注意:(a%c)*(b%c)%c==a*b%c ;
View Code
/*
  ID: dizzy_l1
  LANG: C++
  TASK: nocows
*/
#include<iostream>
#include<cstring>
#include<cstdio>
#define MAXN 200
#define MAXK 100
#define MOD 9901

using namespace std;

long long d[MAXN][MAXK];

FILE *fin  = fopen ("nocows.in", "r");
FILE *fout = fopen ("nocows.out", "w");

int main()
{
    int n,m,k,i,j;
    while(fscanf(fin,"%d %d",&n,&m)==2)
    {
        memset(d,0,sizeof(d));
        for(i=1;i<=m;i++) d[1][i]=1;
        for(i=2;i<=n;i++)
        {
            for(j=1;j<=m;j++)
            {
                for(k=1;k<=i-2;k++)
                {
                    d[i][j]+=d[k][j-1]*d[i-k-1][j-1]%MOD;
                }
            }
        }
        int ans=((d[n][m]-d[n][m-1])%MOD+MOD)%MOD;
        fprintf(fout,"%d\n",ans);
    }
    return 0;
}
posted @ 2012-09-04 21:26  mtry  阅读(685)  评论(0)    收藏  举报