【POJ 3460】 Booksort

【题目链接】

             http://poj.org/problem?id=3460

【算法】

            IDA*

            注意特判答案为0的情况

【代码】

              

#include <algorithm>
#include <bitset>
#include <cctype>
#include <cerrno>
#include <clocale>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <limits>
#include <list>
#include <map>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <utility>
#include <vector>
#include <cwchar>
#include <cwctype>
#include <stack>
#include <limits.h>
using namespace std;

int i,j,n,step,T;
int a[20],b[20];

inline bool check()
{
        int i;
        for (i = 1; i <= n; i++)
        {
                if (b[i] != i)
                        return false;
        }
        return true;
}
inline int calc()
{
        int i,ret = 0;
        for (i = 2; i <= n; i++)
        {
                if (b[i] != b[i-1] + 1)
                        ret++;
        }
        return (ret - 1) / 3 + 1;
}
inline bool dfs(int dep)
{
        int i,j,k,l;
        int tmp[20];
        if (dep == step)
        {
                if (check())
                        return true;
        }
        if (dep + calc() > step) return false;
        for (i = 1; i <= n - 1; i++)
        {
                for (j = 1; j <= n - i; j++)
                {
                        for (k = i + j; k <= n + 1; k++)
                        {
                                for (l = 1; l <= n; l++) tmp[l] = b[l];
                                for (l = i + j; l < k; l++) b[i+l-i-j] = tmp[l];
                                for (l = k - j; l < k; l++) b[l] = tmp[l-k+i+j];
                                if (dfs(dep+1)) return true;
                                for (l = 1; l <= n; l++) b[l] = tmp[l];
                        }
                }
        }
        return false;
}

int main() 
{
        
        scanf("%d",&T);
        while (T--)
        {
                scanf("%d",&n);
                for (i = 1; i <= n; i++) scanf("%d",&a[i]);
                for (i = 0; i <= 4; i++)
                {
                        step = i;
                        for (j = 1; j <= n; j++) b[j] = a[j];
                        if (dfs(0)) 
                        {
                                printf("%d\n",step);
                                break;        
                        }    else step = 5;
                }        
                if (step == 5) printf("5 or more\n");
        }
        
        return 0;
    
}

 

posted @ 2018-07-06 14:33  evenbao  阅读(220)  评论(0)    收藏  举报