HDU - 2510 DFS打表

版权声明:博主的博客不值钱随便转载但要注明出处 https://blog.csdn.net/easylovecsdn/article/details/82810213

刚开始做这道题,超时、超时、超时,而且剪枝优化各种无效,突然看到输入范围n<=24,用我的代码把24敲进去,虽然慢,但是能算出结果,嘿嘿,于是我把1——24所有结构都计算了出来,存放到数组中,你输入那个n我反馈给你那个结果,自己写的dfs就相当于一个计算器,事先将结果算出。

再说一点题外话,下周cqw大佬出征青岛icpc区域赛,作为集训队曾经的一员祝愿他展现出最好的实力,取得佳绩,nuc-acm加油!

以下给出代码:

dfs(计算器,用于计算结果)

#include <bits/stdc++.h>

using namespace std;

int Total[25];
int ans, n, sum;
char m[25];


void Total_init()
{
    Total[1] = 1;
    for (int i = 2; i < 25; i++) Total[i] = Total[i-1] + i;
}


void get_count()
{
    int nn = n;
    while (nn >= 1) {

        for (int i = 1; i <= nn; i++) {

            if (m[i] == '+') sum++;

            if (i < nn) {

                if (m[i] == m[i+1]) m[i] = '+';
                else m[i] = '-';

            }

        }

        nn--;
    }
}



void dfs(int index, int type)     //type值0代表+,1代表-
{
    if (type == 0) m[index] = '+';
    else m[index] = '-';

    if (index == n) {
        sum = 0;
        get_count();
        if (sum == Total[n]/2) ans++;
        return ;
    }

    dfs(index+1, 0);
    dfs(index+1, 1);
}

int main()
{

    Total_init();

    for (int i = 1; i <= 24; i++) {
        cout << i << ":" << Total[i] << endl;
    }

    while (cin >> n && n) {

        if (Total[n]%2 != 0) {
            cout << 0 << endl;
            continue;
        }

        ans = 0;

        dfs(1, 0);
        dfs(1, 1);

        cout << ans << endl;
    }
    return 0;
}

将计算的结果存入数组

int res[25] = {0, 0, 0, 4, 6, 0, 0, 12, 40, 0, 0, 171, 410, 0, 0, 1896, 5160, 0, 0, 32757, 59984, 0, 0, 431095, 822229};

最后输出结果

#include <bits/stdc++.h>

using namespace std;

int res[25] = {0, 0, 0, 4, 6, 0, 0, 12, 40, 0, 0, 171, 410, 0, 0, 1896, 5160, 0, 0, 32757, 59984, 0, 0, 431095, 822229};
int n;


int main()
{

    while (cin >> n && n) {
        cout << n << " " << res[n] << endl;
    }


    return 0;
}

猜你喜欢

转载自blog.csdn.net/easylovecsdn/article/details/82810213
今日推荐