拖着很久没有学习IDA*,觉得老是看不懂,意外发现在家学习效率也不是很低2333
IDA*迭代加深搜索,设置一个深度上界 M,那么找到一个剪枝来判断当前深度D+之后的估计H 与M的大小关系。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <map>
#include <vector>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define eps 1e-8
using namespace std;
const int maxn = 5 + 5;
typedef long long LL;
int a[maxn];
int n;
int judge(){
int ans = 0;
for(int i=0; i<n-1; i++){
if(a[i] + 1 != a[i+1])
ans++;
}
if(a[n-1] != n) ans++;
return ans;
}
bool CorrectSort(){
for(int i=1; i<n; i++){
if(a[i] <= a[i-1]) return false;
}
return true;
}
bool dfs(int d, int top){
if(d*3 + judge() > top*3) return false;
if(CorrectSort()) return true;
int arr[maxn];
int b[maxn];//剪切后剩下的
memcpy(arr, a, sizeof(a));
for(int i=0; i<n; i++){
for(int j=i; j<n; j++){
int cnt = 0;
for(int k=0; k<n; k++)
if(k < i || k > j) b[cnt++] = a[k];
for(int k=0; k<=cnt; k++){//插入不同的位置
int sum = 0;
for(int p=0; p<k; p++) a[sum++] = b[p];
for(int p=i; p<=j; p++) a[sum++] = arr[p];//剪下来的文本
for(int p=k; p<cnt; p++) a[sum++] = b[p];
if(dfs(d+1,top)) return true;
memcpy(a, arr, sizeof(a));
}
}
}
return false;
}
int solve(){
int ans = 5;
for(int top=0; top<5; top++){
if(dfs(0,top)) return top;
}
return ans;
}
int main(){
int kases = 1;
while(scanf("%d",&n) == 1 && n){
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
printf("Case %d: %d\n",kases++,solve());
}
}
/*
6
2 4 1 5 3 6
5
3 4 5 1 2
0
*/