zoukankan      html  css  js  c++  java
  • 【例题 7-10 UVA

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

    在这里输入题意

    【题解】

    迭代加深搜。 很容易想到,最多只要搜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;
    }
    
    
  • 相关阅读:
    计算机操作系统之进程管理
    剑指offer——两个链表的第一个公共结点
    剑指offer——数字在排序数组中出现的次数
    剑指offer——二叉树的深度与平衡二叉树的判断
    剑指offer——数组中只出现一次的数字
    剑指offer——和为s的两个数字VS和为s的连续正数序列
    剑指offer——翻转单词顺序VS左旋转字符串
    剑指offer——扑克牌的顺子
    剑指offer——圆圈中最后剩下的数字
    剑指offer——求1+2+...+n
  • 原文地址:https://www.cnblogs.com/AWCXV/p/8023526.html
Copyright © 2011-2022 走看看