考虑到矩形个数不超过15个,自然首先想到状态压缩DP。对于每个方块,若已经涂色则对应位置为1,否则为0。则最终状态为(1<
dp[state][k] = min(dp[state][k],dp[state+t][color]) ---当color == k时;
dp[state][k] = min(dp[state][k],dp[state+t][color]+1) ---当color != k时。
其中t表示把某个可以涂的方块涂上后,状态值的变化。dp初始化为无穷。最终答案为min(dp[(1<
题目中还有一个约束条件是某方块在涂色前,在其上面并与其直接接触的方块必须先涂好。这里直接对每一个方块进行预处理,记录与它直接接触的方块有哪些,在进行状态转移的时候,判断当前状态,以及当前涂色是否可行即可。
这里用set来记录颜色。(题目中颜色不是按顺序给的,比如有三种颜色,并不意味着是1,2,3;而可以是1,3,10这样的。
用vector记录每个方块的“先前”方块。
#include
#include
#include
#include
#include
#include
using namespace std;
const int SIZE = 1<<15;
const int inf = 0xfffffff;
struct node
{
int lx,ly,rx,ry;
int color;
}rec[16];
int cas,n;
int dp[SIZE][32];
vector v[16];
set st;
int main()
{
scanf("%d",&cas);
while(cas--)
{
scanf("%d",&n);
st.clear();
for(int i=1; i<=n; i++)
{
scanf("%d%d%d%d%d",&rec[i].lx,&rec[i].ly,&rec[i].rx,&rec[i].ry,&rec[i].color);
st.insert(rec[i].color);
}
for(int i=0; i<(1<= rec[i].ry)
continue;
v[i].push_back(k);
}
}
}
for(int s=1; s<(1<::iterator k=st.begin(); k!=st.end(); k++)
{
if(dp[s][*k] == inf)continue;
int state = s+(1<<(i-1));
if(*k == rec[i].color)
dp[state][rec[i].color] = min(dp[state][rec[i].color],dp[s][*k]);
else
dp[state][rec[i].color] = min(dp[state][rec[i].color],dp[s][*k]+1);
}
}
}
int ans = inf;
for(set::iterator i=st.begin(); i!=st.end(); i++)
if(ans > dp[(1<