您的位置:首页 > 大数据 > 人工智能

poj 1691 Painting a Board(状态压缩DP)

2012-10-31 20:02 477 查看
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector> 
using namespace std;

struct sq{
       int lx, ly, rx, ry;
       int col;
       void get(){
            scanf("%d %d %d %d %d", &ly, &lx, &ry, &rx, &col);
            col--;
       } 
       vector<int> upsq;
}a[20];

int n;
#define MAX 32769
int d[MAX][20];
int des;
const int inf = 1000; 

void pre(){
     for (int i = 0; i < n; i++){
         for (int j = 0; j < n; j++){
             if (j == i)continue;
             if (a[j].ry == a[i].ly && ((a[j].rx > a[i].lx && a[j].lx < a[i].rx))){
                         a[i].upsq.push_back(j);
             } 
         }
     }
}

bool check(int st, int cur){
     for (int i = 0; i < a[cur].upsq.size(); i++){
         if (((1<<a[cur].upsq[i])&st) ==0)return false;
     }
     return true;
} 

int doit(int st, int col){
    if (d[st][col] != -1)return d[st][col];
    if (st == des)return d[st][col] = 0;
    d[st][col] = inf; 
    for (int i = 0; i < n; i++)if (((1 << i) & st) == 0 && check(st, i)){
         if (col == a[i].col){
                 d[st][col] = min(doit((st | (1<<i)), col), d[st][col]);
         }
         else {
                 d[st][col] = min(doit((st | (1<<i)), a[i].col) + 1, d[st][col]);
         }
    }
    return d[st][col];
}
 
                  
         
     

int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    int t;
    scanf("%d", &t);
    while (t--){
          scanf("%d", &n);
          for (int i = 0; i < n; i++){ 
               a[i].get();
               a[i].upsq.clear();
          } 
          pre();
          des = 1;
          int ii = 0; 
          while (ii < n)des *= 2, ii++;
          des--;
          //memset(d, -1, sizeof(d)); 
          for (int i = 0; i <= des; i++)
          for (int j = 0; j < 20; j++)
              d[i][j] = -1; 
          int ans = 100; 
         // for (int i = 0; i < n; i++)printf("%d %d $", a[i].upsq.size(), a[i].upsq.size()?a[i].upsq[0]:-1);puts(""); 
          for (int i = 0; i < n; i++){
              doit(0, a[i].col);
              ans = min(ans, d[0][a[i].col]);
          }
          ans++; 
          printf("%d\n", ans);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: