poj1037 DP

转载:http://archive.cnblogs.com/a/2122079/
up[n][k]         长度为n以k开始的,前两个数呈上升趋势的数列的个数
down[n][k]     长度为n以k开始的,前两个数呈下降趋势的数列的个数
up[n][k] = sigma(down[n-1][i])      k<=i<=n-1
down[n][k]= sigma(up[n-1][i])        1<=i<=k-1
第一个满足 sigma(up[n][i]+down[n][i])>=c 的i即为第一位a1
c1=c-(up[n][a1]+down[n][a1])
第一个满足 sigma(up[n-1][i])>=c1 1<=i=c1    a1<=i<=n-1 为a2
一旦确定a1,a2就可以与确定下面是up还是down,两者交替.


for (long long i = 1; i < n; i++)
            if (ans[i] >= t)
                ans[i]++;
算法中的这三行非常精妙,虽然ans[n]已经使用,但是却不影响g[][]高低计数的特征,最后只需作如下处理:大于ans[n]的直接加1,以起到忽视掉选中的高度为t的效果,不影响局部正确性。递归之后,自然也不影响整体正确性。

#include 
#include 
#include 
#include 
using namespace std;

#define maxn 30

struct Node
{
    long long up, down;
} g[maxn][maxn];

long long n;
long long c;
long long ans[maxn];

void getfirst(long long n, long long c, bool u)
{
    if (n == 0)
        return;
    long long t;
    long long sum;
    if (!u)
    {
        sum = 0;
        t = ans[n + 1];
        while (sum + g[n][t].down < c)
        {
            sum += g[n][t].down;
            t++;
        }
    }
    else
    {
        sum = 0;
        t = 1;
        while (sum + g[n][t].up < c)
        {
            sum += g[n][t].up;
            t++;
        }
    }
    ans[n] = t;
    getfirst(n - 1, c - sum, !u);
    for (long long i = 1; i < n; i++)
        if (ans[i] >= t)
            ans[i]++;
}

int main()
{
    //freopen("t.txt", "r", stdin);
    g[1][1].up = 1;
    g[1][1].down = 1;
    for (long long i = 2; i <= 20; i++)
    {
        for (long long j = 1; j <= i; j++)
        {
            g[i][j].up = g[i][j].down = 0;
            for (long long k = j; k <= i - 1; k++)
                g[i][j].up += g[i - 1][k].down;
            for (long long k = 1; k <= j - 1; k++)
                g[i][j].down += g[i - 1][k].up;
        }
    }
    long long x;
    scanf("%lld", &x);
    while (x--)
    {
        scanf("%lld%lld", &n, &c);

        long long t = 1, sum = 0;
        while (sum + g[n][t].down + g[n][t].up < c)
        {
            sum += g[n][t].down + g[n][t].up;
            t++;
        }
        ans[n] = t;
        if (sum + g[n][t].down < c)
            getfirst(n - 1, c - sum - g[n][t].down, false);
        else
            getfirst(n - 1, c - sum, true);
        for (long long i = 1; i < n; i++)
            if (ans[i] >= t)
                ans[i]++;

        printf("%lld", ans[n]);
        for (int i = n - 1; i >= 1; i--)
            printf(" %lld", ans[i]);
        putchar('\n');
    }
    return 0;
}


你可能感兴趣的:(POJ)