Problem E
Editing a Book
You have n equal-length paragraphs numbered 1 to n. Now you want to arrange them in the order of 1, 2, ..., n. With the help of a clipboard, you can easily do this: Ctrl-X (cut) and Ctrl-V (paste) several times. You cannot cut twice before pasting, but you can cut several contiguous paragraphs at the same time - they'll be pasted in order.
For example, in order to make {2, 4, 1, 5, 3, 6}, you can cut 1 and paste before 2, then cut 3 and paste before 4. As another example, one copy and paste is enough for {3, 4, 5, 1, 2}. There are two ways to do so: cut {3, 4, 5} and paste after {1, 2}, or cut {1, 2} and paste before {3, 4, 5}.
Input
The input consists of at most 20 test cases. Each case begins with a line containing a single integer n (1 < n < 10), the number of paragraphs. The next line contains a permutation of 1, 2, 3,..., n. The last case is followed by a single zero, which should not be processed.Output
For each test case, print the case number and the minimal number of cut/paste operations.Sample Input
6 2 4 1 5 3 6 5 3 4 5 1 2 0
Output for the Sample Input
Case 1: 2 Case 2: 1
Rujia Liu's Present 2: A Big Contest of Brute Force
Adapted from ACM/ICPC Kanpur Site 2001-2001
紫书上的例题。
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
struct State
{
int s[11];
};
int n;
State s0, goal;
int maxd;
int kase;
void init()
{
for(int i=0;i<11;i++){
goal.s[i]=s0.s[i]=i+1;
}
kase=0;
}
State cpy(State &p, int x, int num, int pos) //剪切黏贴的操作
{
State t;
int i=0;
if(x<pos){
for(int j=0;j<x;j++){
t.s[i++]=p.s[j];
}
for(int j=x+num;j<=pos;j++){
t.s[i++]=p.s[j];
}
for(int j=x;j<x+num;j++){
t.s[i++]=p.s[j];
}
for(int j=pos+1;j<n;j++){
t.s[i++]=p.s[j];
}
}
else {
for(int j=0;j<=pos;j++){
t.s[i++]=p.s[j];
}
for(int j=x;j<x+num;j++){
t.s[i++]=p.s[j];
}
for(int j=pos+1;j<x;j++){
t.s[i++]=p.s[j];
}
for(int j=x+num;j<n;j++){
t.s[i++]=p.s[j];
}
}
return t;
}
bool dfs(State t, int d) //状态搜索
{
int h=0;
if(d>maxd) return false;
if(d==maxd&&memcmp(t.s, goal.s, sizeof(int)*n)==0) return true;
if(d==maxd) return false;
for(int i=0;i<n-1;i++){
if(t.s[i]+1!=t.s[i+1]) h++;
}
if(3*d+h>3*maxd) return false; //估价函数的剪枝
for(int i=0;i<n;i++){
for(int j=1;i+j-1<n;j++){
for(int k=0;k<n;k++){
if(k>=i&&k<i+j*(i+1)) continue;
if(dfs(cpy(t, i, j, k), d+1)) return true;
}
}
}
return false;
}
int main()
{
init();
while(scanf("%d", &n)!=EOF&&n){
//
for(int i=0;i<n;i++){
scanf("%d", &s0.s[i]);
}
printf("Case %d: ", ++kase);
for(maxd=0;maxd<n;maxd++){
if(dfs(s0, 0)) {
printf("%d\n", maxd);
break;
}
}
}
return 0;
}