【USACO】Cow Pedigrees

DP,方程关系是,高为K,node数为N的树,相当于,(1)左子树高为K-1,右子树高<=K-2;(2)左子树高<=K-2,右子树高为K-1;(3)做右子树高度都为K-1;三种情况的和。

(1)和(2)是对称的,所以求一个*2即可。

求(1)时,需要枚举左子树的node数量。

下面是DP方程:

设a[i][j]是高为j,node数为i的子树的数量。b[i][j]是高<=j,node数为i的树的数量。

               i - 1

a[i][j] =   Σ ( (a[m][j - 1] * b[i - m - 1][j - 2]) * 2 + a[m][j - 1] * a[i - m - 1][j - 1]);

           m = 2*(j - 1) - 1


/*
ID :
LANG: C++11
TASK: nocows
 */

#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

int main()
{
    freopen("nocows.in", "r", stdin);
    freopen("nocows.out", "w", stdout);
    std::ios::sync_with_stdio(false);

    int N, K;
    cin >> N >> K;
    int a[205][105] = {};
    int b[205][105] = {};
    a[1][1] = 1;
    b[1][1] = 1;
    for (int i = 0; i < 205; i ++)
        a[i][0] = 1;
    for (int j = 2; j <= K; j ++) {
        for (int i = 2 * j - 1; i <= N; i += 2) {
            for (int m = 2 * j - 3; m <= i - 1; m += 2) {
                a[i][j] += a[m][j - 1] * b[i - 1 - m][j - 2] * 2;
                a[i][j] += a[m][j - 1] * a[i - 1 - m][j - 1];
                a[i][j] %= 9901;
                /* 注释里是如果没有数组b时候的做法,但复杂度会高很多。
                for (int t = 1; t <= j - 2; t ++){
                    a[i][j] += a[m][j - 1] * a[i - 1 - m][t] * 2;
                    a[i][j] %= 9901;
                }
                a[i][j] += a[m][j - 1] * a[i - 1 - m][j - 1];
                a[i][j] %= 9901;
                 */

            }
        }
        for (int i = 1; i <= N; i += 2){
            b[i][j] += b[i][j - 1] + a[i][j];
            b[i][j] %= 9901;
        }
    }

    cout << a[N][K] << endl;
    return 0;
}

你可能感兴趣的:(DP,USACO)