估价函数很经典,每个值的后继值错误的个数除以3。因为一次操作最多改变3个值的后继值。
1A,IDA*已经写得很纯熟了。
#include <iostream>
#include <cmath>
using namespace std;
int a[25],n,bound,cas;
int ans;
int h(int *a) {
int hv = 0;
if (a[1]!=1) hv++;
for (int i=1;i<n;i++)
if (a[i+1]!=a[i]+1) hv++;
return (hv+2)/3;
}
void trans(int *a,int p1,int p2,int p3) {
int tmp[20];
for (int i=p1;i<=p2;i++)
tmp[i]=a[i];
for (int i=p2+1;i<=p3;i++)
a[i-p2+p1-1]=a[i];
for (int i=p1+p3-p2;i<=p3;i++)
a[i]=tmp[i+p2-p3];
}
int dfs(int *a,int dep) {
int hv = h(a);
//printf("%d %d\n",dep,hv);
if (dep>=5) {
ans = 2;
return 5;
}
if (hv + dep > bound) return hv+dep;
if (hv==0) {
ans = 1;
return dep;
}
int next_bound = 10000;
for (int i=1;i<n;i++)
for (int j=i+1;j<=n;j++)
for (int k=i;k<j;k++) {
int tmp[20];
for (int r=1;r<=n;r++) tmp[r]=a[r];
trans(tmp,i,k,j);
int new_bound = dfs(tmp,dep+1);
if (ans!=0) return new_bound;
next_bound = min(next_bound,new_bound);
}
return next_bound;
}
void ida_star() {
bound = h(a);
ans = 0;
while (!ans && bound<=10)
bound = dfs(a,0);
if (ans==1) printf("%d\n",bound);
else printf("5 or more\n");
}
int main() {
scanf("%d",&cas);
for (int tt=1;tt<=cas;tt++) {
scanf("%d",&n);
for (int i=1;i<=n;i++)
scanf("%d",&a[i]);
if (h(a)==0) {
printf("0\n");
continue;
}
ida_star();
}
return 0;
}