标签:
#include <cstdio> #include <iostream> #include <string> #include <sstream> #include <cstring> #include <stack> #include <queue> #include <algorithm> #include <cmath> #include <map> #define PI acos(-1.0) #define ms(a) memset(a,0,sizeof(a)) #define msp memset(mp,0,sizeof(mp)) #define msv memset(vis,0,sizeof(vis)) using namespace std; //#define LOCAL int sign[10]; int mp[10]; int ans,res[10]; bool check(int n) { switch(n) { case 1: { if(abs(mp[0]-mp[1])==1)return 0; return 1; } case 2: { if(abs(mp[0]-mp[2])==1)return 0; if(abs(mp[1]-mp[2])==1)return 0; return 1; } case 3: { if(abs(mp[0]-mp[3])==1)return 0; if(abs(mp[2]-mp[3])==1)return 0; return 1; } case 4: { if(abs(mp[2]-mp[4])==1)return 0; if(abs(mp[1]-mp[4])==1)return 0; return 1; } case 5: { if(abs(mp[1]-mp[5])==1)return 0; if(abs(mp[2]-mp[5])==1)return 0; if(abs(mp[3]-mp[5])==1)return 0; if(abs(mp[4]-mp[5])==1)return 0; return 1; } case 6: { if(abs(mp[2]-mp[6])==1)return 0; if(abs(mp[3]-mp[6])==1)return 0; if(abs(mp[5]-mp[6])==1)return 0; return 1; } case 7: { if(abs(mp[4]-mp[7])==1)return 0; if(abs(mp[5]-mp[7])==1)return 0; if(abs(mp[6]-mp[7])==1)return 0; return 1; } } return 1; } void dfs(int n) { if(n==7) { if(mp[n]==0) { for(int i=1; i<=8; i++) { if(sign[i]==0) { mp[n]=i; sign[i]=1; if(check(n)) { ans++; for(int j=0; j<8; j++) res[j]=mp[j]; } sign[i]=0; mp[n]=0; } } } else { if(check(n)) { ans++; for(int j=0; j<8; j++) res[j]=mp[j]; } } } else { if(mp[n]==0) { for(int i=1; i<=8; i++) { if(sign[i]==0) { mp[n]=i; sign[i]=1; if(check(n))dfs(n+1); sign[i]=0; mp[n]=0; } } } else { if(check(n))dfs(n+1); } } return; } int main() { #ifdef LOCAL freopen("in.txt", "r", stdin); #endif // LOCAL ios::sync_with_stdio(false); int n,cas=0; cin>>n; while(n--) { cas++; ans=0,ms(res),ms(mp),ms(sign); for(int i=0; i<8; i++) { cin>>mp[i]; if(mp[i]!=0)sign[mp[i]]=1; } for(int i=0; i<8; i++) { if(mp[i]==0) { dfs(i); break; } } if(ans==1) { printf("Case %d:",cas); for(int i=0; i<8; i++) printf(" %d",res[i]); printf("\n"); } else if(ans==0)printf("Case %d: No answer\n",cas); else printf("Case %d: Not unique\n",cas); } return 0; }
HDU 2514 Another Eight Puzzle(DFS)
标签:
原文地址:http://www.cnblogs.com/gpsx/p/5185542.html