【例题 7-10 UVA - 11212】Editing a Book

【链接】 我是链接,点我呀:)
【题意】

在这里输入题意

【题解】

迭代加深搜。 很容易想到,最多只要搜8层就可以得到答案了 ->最多8下肯定可以还原。 则枚举一下最大层数。然后做个深搜就好。 优化。 设0..n每个数字的后继不为a[i]+1的个数为cnt 则每次操作显然最多只能减少3个cnt.. 可以画图分析一下。 则可以拿这个来做剪枝。。 然后插入的过程可以用链表来实现。

【代码】

/*
  	1.Shoud it use long long ?
  	2.Have you ever test several sample(at least therr) yourself?
  	3.Can you promise that the solution is right? At least,the main ideal
  	4.use the puts("") or putchar() or printf and such things?
  	5.init the used array or any value?
  	6.use error MAX_VALUE?
  	7.use scanf instead of cin/cout?
  	8.whatch out the detail input require
*/
#include <bits/stdc++.h>
using namespace std;

const int N = 10;

int n,a[N+5],l[N+5],r[N+5],templ[N+5],tempr[N+5],maxdep,ans = -1;

void Move(int i,int j,int pos){
     r[l[i]] = r[j];
     l[r[j]] = l[i];
     l[r[pos]] = j;
     r[j] = r[pos];

     r[pos] = i;
     l[i] = pos;
}

void dfs(int dep){
 	if (dep==maxdep){
 		for (int i = 0;i <= n;i++)
            if (a[r[i]]!=a[i]+1)
                return;

 		if (ans==-1) ans = dep;
 		else ans = min(ans,dep);

		return;
	}

	int cnt = 0;
	for (int i = 0;i <= n;i++)
		if (a[r[i]]!=a[i]+1)
			cnt++;
	int delta = maxdep-dep;
	if (delta*3<cnt) return;

	for (int i = r[0];i != n+1;i=r[i])
		for (int j = i;j != n+1;j = r[j]){
		 	//1,2,3..i..j,j+1....n
			for (int pos = 0;pos!=l[i];pos=r[pos]){
                 int pre = l[i];
                 Move(i,j,pos);
				 dfs(dep+1);
                 Move(i,j,pre);
		 	}
		 	for (int pos = r[j];pos != n+1;pos = r[pos]){
			 	 int pre = l[i];
                 Move(i,j,pos);
				 dfs(dep+1);
                 Move(i,j,pre);
		 	}
		}
	return;
}

int main(){
	#ifdef LOCAL_DEFINE
	    freopen("F:\\c++source\\rush_in.txt", "r", stdin);
	#endif
	ios::sync_with_stdio(0),cin.tie(0);
	int kase = 0;
	while (cin >> n && n){
		cout <<"Case "<<++kase<<": ";
		for (int i = 1;i <= n;i++) cin >> a[i];
		for (int i = 1;i <= n+1;i++) l[i] = i-1,r[i] = i+1;
		r[0] = 1;
		a[n+1] = n+1;
		ans = -1;
		for (maxdep = 0;maxdep <= 9;maxdep++){
            dfs(0);
            if (ans!=-1) break;
		}
		cout << ans << endl;
	}
	return 0;
}

posted @ 2017-12-11 16:01  AWCXV  阅读(172)  评论(0编辑  收藏  举报