【迭代加深搜索】 Editing a Book

B - Editing a Book

You have n equal-length paragraphs numbered 1 to n. Now you want to arrange them in the order
of 1, 2, … , n. With the help of a clipboard, you can easily do this: Ctrl-X (cut) and Ctrl-V (paste)
several times. You cannot cut twice before pasting, but you can cut several contiguous paragraphs at
the same time - they’ll be pasted in order.
For example, in order to make {2, 4, 1, 5, 3, 6}, you can cut 1 and paste before 2, then cut 3 and
paste before 4. As another example, one copy and paste is enough for {3, 4, 5, 1, 2}. There are two
ways to do so: cut {3, 4, 5} and paste after {1, 2}, or cut {1, 2} and paste before {3, 4, 5}.

Input

The input consists of at most 20 test cases. Each case begins with a line containing a single integer n
(1 < n < 10), thenumber of paragraphs. The next line contains a permutation of 1, 2, 3, … , n. The
last case is followed by a single zero, which should not be processed.

Output

For each test case, print the case number and the minimal number of cut/paste operations.

Sample Input

6
2 4 1 5 3 6
5
3 4 5 1 2
0

Sample Output

Case 1: 2
Case 2: 1

【解析】

这道题应该也没有多深的难度。其特点是需要我们控制它搜索的深度。而其他的地方则是暴力枚举罢了。
AC代码:

#include
#include
using namespace std;
#define MAXN 15
int n,a[MAXN];
int D(int a[])//判断错误点 
{
    int cnt=0;
    for(int i=0;i1;i++)
        if(a[i]+1!=a[i+1]) cnt++;
    if(a[n-1] !=n) cnt++;
    return cnt;
}
bool dfs(int d,int maxd,int a[])
{
    int t=D(a);
    if(!t) return 1;
    if(d*3+t>maxd*3) return 0;//理想状态(如果我们已经改变的位置加上需要改变的超过了最大深度则失效)失效
    int Next[MAXN];
    int len;
    for(int i=1;i<=n;i++)//起点 
        for(int j=i;j<=n;j++)//终点 
            for(int k=1;k//插入点 
            {
                memcpy(Next,a,sizeof Next);
                len=j-i+1;
                for(int p=0;p1]=a[i+p-1];//复制 
                len=i-k;//n-j+i-1
                for(int p=0;p1]=a[i-p-2];
                if(dfs(d+1,maxd,Next)) return 1;
             } 
    return 0;
}
int solve()
{
    if(!D(a)) return 0;
    int max_ans=12;
    for(int maxd=1;maxdif(dfs(0,maxd,a)) return maxd;
    return max_ans;
}
int main()
{
    int kase=0;
    while(scanf("%d",&n)&&n)
    {
        for(int i=0;iscanf("%d",&a[i]);
        printf("Case %d: %d\n",++kase,solve());
    }
    return 0;
}

你可能感兴趣的:(openjudge题库,刷题日志)