poj 1020 Anniversary Cake

/*
** poj 1020 Anniversary Cake
** http://poj.org/problem?id=1020
** antsmall 2010-12-4
** this problem is about cutting a square-shaped cake into specifying pieces which lead to no waste
** i.e. the cake is 4x4, and can be cut into pieces of 1x1 1x1 1x1 1x1 1x1 3x3 1x1 1x1
** 
** p.s. today, we are happy to see ximei, a funny little girl of my colleague Mr Liu, whom helps 
** me a lot in my daily work, and a master of database and etl
*/

#include <iostream>
using namespace std;


char* STR_S = "KHOOOOB!"; // for success
char* STR_F = "HUTUTU!";   // for fail

int t;   // num of test cases
int s;   // side of the cake
int n;   // pieces num of each testcase
int cnt[11]; // side of each piece, and there are at most 16 pieces 
int cols[41]; // the used len of each column 
int cakeSize; // size of the cake
int piecesSize; // sum of the pieces' size

// judge is it cutable, using dfs
bool canCut(int used) {
if(used == n) 
   return true;

int minLen = 41;
int minInd = 41;

// find the min col to start put 
for(int i = 0; i < s; i++) {
   if(cols[i] < minLen) {
    minLen = cols[i]; minInd = i;
   }
}

for(int i = 10; i >= 1; i--) {
   if(cnt[i] > 0 && minLen + i <= s && minInd + i <= s) {
    // check if can reach the request
    bool found = true;
    for(int j = minInd; j <= minInd + i - 1; j++) {
     if(cols[j] > minLen) {
      found = false; break;
     }
    }
    if(found) {
     for(int j = minInd; j <= minInd + i - 1; j++) cols[j] += i;
     cnt[i]--;
     // dfs
     if(canCut(used + 1)) return true;
     cnt[i]++;
     for(int j = minInd; j <= minInd + i - 1; j++) cols[j] -= i;
    }
   }
}

return false;
}

int main(){
int side;
scanf("%d", &t);

while(t--) {
   memset(cols, 0, sizeof(cols));
   memset(cnt, 0, sizeof(cnt));

   scanf("%d%d", &s, &n);
   cakeSize   = s*s; 
   piecesSize = 0;
   for(int i = 0; i < n; i++) {
    scanf("%d", &side);
    piecesSize += side*side;
    cnt[side]++;
   }
  
   // judge whether can cut
   if(cakeSize == piecesSize && canCut(0)) {
    printf("%s\n", STR_S); // yes 
   } else {
    printf("%s\n", STR_F); // no 
   }

}
//system("pause");
return 0;
}

你可能感兴趣的:(F#,J#)