dfs 剪枝 排书问题

给定n本书,编号为1-n。

在初始状态下,书是任意排列的。

在每一次操作中,可以抽取其中连续的一段,再把这段插入到其他某个位置。

我们的目标状态是把书按照1-n的顺序依次排列。

求最少需要多少次操作。
输入格式

第一行包含整数T,表示共有T组测试数据。

每组数据包含两行,第一行为整数n,表示书的数量。

第二行为n个整数,表示1-n的一种任意排列。

同行数之间用空格隔开。
输出格式

每组数据输出一个最少操作次数。

如果最少操作次数大于或等于5次,则输出”5 or more”。

每个结果占一行。
数据范围

1≤n≤15

输入样例:

3
6
1 3 4 6 2 5
5
5 4 3 2 1
10
6 8 5 3 4 7 2 9 1 10

输出样例:

2
3
5 or more

解题报告:这道题要用dfs做,用估价函数A*来剪枝,我们不难发现出,n个数字最后的排序是对应n-1个关系对 1——2 2——3…我们每次把一整块连续的书插入到后面时,最多改变3个关系,所以我们可以求出不正确的关系的数量再/3上取整,dfs搜索有两个参数,一个是当前的深度,和最大的深度,我们来枚举最大深度的大小,如果不满足return false。

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const   int N=16;
int q[N];
int w[5][N];
int n;
int f()
{
    int cnt=0;
    for(int i=0;i<n-1;i++)
    if(q[i]!=q[i+1]-1)  cnt++;
    return (cnt+2)/3;
}
bool dfs(int u,int max_depth)
{
    if(f()+u>max_depth)     return false;
    if(f()==0  )        return true;
    for(int len=1;len<=n;len++)
    for(int l=0;l+len-1<n;l++)
    {
        int r=l+len-1;
        for(int k=r+1;k<n;k++)
        {
            memcpy(w[u],q,sizeof q);
             int x,y;
             for(x=l,y=r+1;y<=k;x++,y++)    q[x]=w[u][y];
             for(y=l;y<=r;y++,x++)      q[x]=w[u][y];
             if(dfs(u+1,max_depth))     return true;
             memcpy(q,w[u],sizeof q);
        }
    }
    return false;
    
    
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
      cin>>n;
      for(int i=0;i<n;i++)
      cin>>q[i];
      int depth=0;
      while(depth<5&&!dfs(0,depth))  depth++;
      if(depth>=5)  cout<<"5 or more"<<endl;
      else      cout<<depth<<endl;
    }
    return 0;
}
发布了215 篇原创文章 · 获赞 9 · 访问量 3549

猜你喜欢

转载自blog.csdn.net/qq_45961321/article/details/105157111