jzoj5441【NOIP2017提高A组冲刺11.1】序列

来源:互联网 发布:linux 安装redis 编辑:程序博客网 时间:2024/06/05 10:32

题目

Description

给定一个1~n的排列x,每次你可以将x1~xi翻转。你需要求出将序列变为升序的最小操作次数。有多组数据。

Input

第一行一个整数t表示数据组数。
每组数据第一行一个整数n,第二行n个整数x1~xn。

Output

每组数据输出一行一个整数表示答案。

Sample Input

1
8
8 6 1 3 2 4 5 7

Sample Output

7

Data Constraint

对于100%的测试数据,t=5,n<=25。
对于测试点1,2,n=5。
对于测试点3,4,n=6。
对于测试点5,6,n=7。
对于测试点7,8,9,n=8。
对于测试点10,n=9。
对于测试点11,n=10。
对于测试点i (12<=i<=25),n=i。

题解

迭代加深+估价函数
P.S.
迭代加深在一些搜索程度比较浅的题目中有让人意想不到的结果,较强的估价函数也可以做到指数级别的优化
看到这种数据基本就是搜索了,要多往这个方向想

考虑迭代搜索(就是从小到大枚举答案,知道某一个答案可行就输出),加上一个估价函数 fo(i,2,p+1) if (abs(c[i]-c[i-1])!=1) gu++;(如果相邻的两个数是不同的我们不可能在一次操作中让它们都归位,或者说每一次操作只会改变一对相邻的数)然后就O(能过)了cc

贴代码

#include<iostream>#include<algorithm>#include<cstdio>#include<cstring>#include<cmath>#define fo(i,a,b) for(i=a;i<=b;i++)using namespace std;const int maxn=30;int a[maxn],b[maxn],c[maxn];int i,j,k,l,n,x,y,o,t,now,ans;bool bz;void dfs(int p,int cq){    if (cq>ans) return;    if (bz==true) return;    while (c[p]==p && p>0) p--;     if (p==0) bz=true; else{        int i,gu=0;        fo(i,2,p+1) if (abs(c[i]-c[i-1])!=1) gu++;        if (gu+cq>ans) return;        fo(i,2,p){            fo(j,1,i) b[j]=c[i-j+1];            fo(j,1,i) c[j]=b[j];            dfs(p,cq+1);            fo(j,1,i) b[j]=c[i-j+1];            fo(j,1,i) c[j]=b[j];        }    }}int main(){    freopen("sequence.in","r",stdin);    freopen("sequence.out","w",stdout);    scanf("%d",&t);    fo(o,1,t){        scanf("%d",&n);        fo(i,1,n) scanf("%d",&a[i]);        fo(i,1,n) c[i]=a[i];        now=n;        while (c[now]==now && now>0) now--;        fo(ans,0,2*n-2){            bz=false;            dfs(now,0);            if (bz==true) break;        }        printf("%d\n",ans);    }    return 0;}
阅读全文
0 0