【暴力搜索】[UVa 11212]Editing a Book

就是纯暴力,每次枚举起点中点和向后移动的步数,加上if(dif(now) + 3 * (u-1) > 3 * maxd) return false;优化dif(now)表示每一位的后面是否是正确的

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct State{int s[11];};
int n, maxd;
int dif(State s){
    int ret = 0;
    for(int i=1;i<n;i++)
        if(s.s[i+1]!=s.s[i]+1)
            ret++;
    if(s.s[n]!=n) ret++;
    return ret;
}
State rret;
void move_back(State st, int i, int j, int bk){
    for(int k=1; k<= bk; k++) rret.s[i+k-1] = st.s[j+k];
    for(int k=i; k<=j; k++) rret.s[k+bk] = st.s[k];
}
bool dfs(int u, State now){
    State tmp;
    if(u > maxd) return dif(now) == 0;
    if(dif(now) + 3 * (u-1) > 3 * maxd) return false;
    int bend;
    for(int i=1;i<=n;i++)
        for(int j=i;j<=n;j++){
            bend = n-j;
            for(int back=1;back<=bend; back++){
                rret = now;
                move_back(now, i, j, back);tmp = rret;
                if(dfs(u+1, tmp)) return true;
            }
        }
    return false;
}
int main(){
    int ccnt=0;State be;
    while(scanf("%d", &n)!=EOF && n){
        for(int i=1;i<=n;i++) scanf("%d", &be.s[i]);
        maxd = 0;
        while(!dfs(1, be)) maxd++;
        printf("Case %d: %d\n",++ccnt, maxd);
    }

    return 0;
}

posted on 2015-07-21 09:38  JeremyGuo  阅读(154)  评论(0编辑  收藏  举报

导航