Another iteration deepens the search, from small to large enumeration caps. The key pruning part is to write the heuristic function, which is more difficult.
But after each cut, the number of incorrect numbers minus three is very good to understand, because we calculate the number of incorrect numbers is to see whether the current number +1 is equal to the next number. So the subsequent number of a maximum of 3 digits per cut has changed. Then the pruning conditions are obvious.
The code is as follows:
#include <bits/stdc++.h>using namespace Std;const int maxn = 15;int N,a[15],kase = 0,maxd;bool Is_sort () {for (int i=0;i<n-1;i++) if (A[i] >= a[i+1]) return false; return true;} int h () {int cnt = 0; for (int i=0;i<n-1;i++) if (a[i]+1! = a[i+1]) cnt++; if (a[n-1]! = n) cnt++; return CNT;} BOOL Dfs (int d,int maxd) {if (d*3 + H () > Maxd*3) return false;//pruning if (d = = Maxd) {if (Is_sort ()) return T Rue return false; } int B[MAXN],OLDA[MAXN]; memcpy (Olda,a,sizeof (a));//Copy to facilitate recovery for (int. i=0;i<n;i++) {for (int j=i;j<n;j++) {///Enumerate the endpoints of successive intervals to be clipped [i,j] int cnt = 0; for (int k=0;k<n;k++) if (k < I | | k > J) b[cnt++] = a[k]; Splicing the non-clipped section for (int k=0;k<cnt;k++) {//enum will be inserted before k int cnt2 = 0; for (int p=0;p<k;p++) a[cnt2++] = b[p]; The part before the insertion point for (int p=i;p<=j;p++) a[cnt2++] = olda[p]; Inserted (clipped part) foR (int p=k;p<cnt;p++) a[cnt2++] = b[p];//After the insertion point if (DFS (D+1,MAXD)) return true; memcpy (A,olda,sizeof (a));//Copy Back}}} return false; int main () {while (~SCANF ("%d", &n) &&n) {for (int i=0;i<n;i++) scanf ("%d", &a[i]); for (maxd = 0; Maxd < 8; ++maxd) {if (Dfs (0,MAXD)) break; } printf ("Case%d:%d\n", ++kase,maxd); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
11212-editing a book (ida* algorithm)