UVA 12113 - Overlapping Squares

#include <cstdio>
#include <set>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = (1<<9);
int a[9][8]={{1,3,9,13,18,19,21,22}};
int clean[9][4]={{10,11,12,20}};
void init(){
 int kk=1;
    for(int d = 0 ;d<=2;d++)
      for(int l = 0;l<=2;l++)if(d||l){
           //cout<<kk<<": ";
           for(int i=0;i<8;i++){
               a[kk][i] = a[0][i]+d*9+l*2;
           }
           for(int i=0;i<4;i++){
               clean[kk][i]=clean[0][i]+d*9+l*2;
           }
           kk++;
    }
}
int bitcount(int x){return x==0 ? 0 : bitcount(x/2)+(x&1);}
int b[10],c[45],maze[45];
char str[100];
int read_input(){
   int cnt=0,kk=0;
   for(int i=0;i<5;i++){
      if(gets(str)==NULL) return -1;
      if(str[0]=='0') return -1;
      for(int j=0;j<9;j++){
         maze[kk++] = str[j] == 32 ? 0 : 1;
         if(str[j]!=32) cnt++;
      }
   }
   return cnt;
}
inline void stick(int p,int& cnt){
  for(int j=0;j<8;j++){
   if(c[a[p][j]]==0) cnt++;
   c[a[p][j]]=1;
  }
    for(int j=0;j<4;j++){
     if(c[clean[p][j]] == 1) cnt--;
     c[clean[p][j]]=0;
   }
}
int main()
{
   init();
   int kase=1,goal_cnt;
   while((goal_cnt = read_input())&&goal_cnt!=-1){
    void debug();
    bool flag=false;
    for(int s=0;s<maxn;s++){
         int n = bitcount(s);
         if(n > 6 || 8*n<goal_cnt) continue;
         int k=0;
         for(int i=0;i<9;i++) if((s>>i)&1)
            b[k++] = i;

         do{
          memset(c,0,sizeof(c));
          int cnt=0;
          for(int i=0;i<n;i++){
              int p = b[i];
              stick(p,cnt);
          }
           if(cnt==goal_cnt){
            int ok=1;
            for(int i=0;i<45;i++)if(maze[i]!=c[i]){
             ok =0; break;
            }
            if(ok) {flag=true;}
           }
          if(flag) break;
         }while(next_permutation(b,b+k));
    }
    printf("Case %d: %s\n",kase++,flag ? "Yes":"No");
   }
    return 0;
}
void debug(){
  memset(c,0,sizeof(c));
   int cnt=0;
   stick(3,cnt);
   stick(4,cnt);
   stick(7,cnt);
   for(int i=0;i<45;i++) cout<<c[i]<<" ";
   cout<<endl;
   cout<<cnt<<"**\n";
}


你可能感兴趣的:(UVA 12113 - Overlapping Squares)