hdu2514 Another Eight Puzzle (全排列、暴力)


http://acm.hdu.edu.cn/showproblem.php?pid=2514


n = 8, 我直接用了next_permutation 全排列 , 然后对每一个排列进行即可。


#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int a[10];
int b[10];
int ans[10];
int pos[10];
bool used[10];
int n, flag;
int map[8][8]= {
    {0,1,1,1,0,0,0,0},
    {1,0,1,0,1,1,0,0},
    {1,1,0,1,1,1,1,0},
    {1,0,1,0,0,1,1,0},
    {0,1,1,0,0,1,0,1},
    {0,1,1,1,1,0,1,1},
    {0,0,1,1,0,1,0,1},
    {0,0,0,0,1,1,1,0},
};
bool judge() {
    int i, j;
    for(i=0; i<8; i++)
        for(j=0; j<8; j++)
            if(map[i][j]&&(a[i]-a[j]==1||a[j]-a[i]==1) ) return false;
    return true;
}
int main() {
    int T, i, flag,f,  cnt = 0,n;
    scanf("%d",&T);
    while(T--) {
        printf("Case %d:",++cnt);
        n = 0;
        memset(used,0,sizeof(used));
        for(i=0; i<8; i++) {
            scanf("%d",&a[i]);
            if(a[i]==0) pos[n++] = i;
            used[ a[i] ] = true;
        }
        n = 0;
        for(i=1; i<=8; i++) if(!used[i]) b[n++] = i;
        flag = 0;
        do {
            for(i=0; i<n; i++)
                a[ pos[i] ] = b[i];
            if(judge()) {
                if(++flag>1) break;
                for(i=0; i<8; i++) ans[i] = a[i];
            }
        } while(next_permutation(b,b+n));
        if(flag==1) {
            for(i=0; i<8; i++) printf(" %d",ans[i]);
        } else if(flag==0) printf(" No answer");
        else printf(" Not unique");
        printf("\n");
    }
    return 0;
}


你可能感兴趣的:(hdu2514 Another Eight Puzzle (全排列、暴力))