lightoj 1018 (状态压缩DP)

时间:2021-12-05 23:04:54

设dp[s]表示状态s下所需要的线段的个数,s的二进制中第x位为1就表示该状态下第x个点没被线段覆盖。需要预处理出来在任意两点之间连线所覆盖点的状态O(n^3),然后记忆化搜索即可。

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN = 16;
int n, dp[1 << MAXN], s[MAXN][MAXN];
struct Point{
int x, y;
bool isOnLine(const Point &A, const Point &B){
return (A.y-y)*(x-B.x) == (A.x-x)*(y-B.y);
}
};
Point P[MAXN];
void init(){
memset(dp, 0x3f, sizeof dp);
memset(s, 0, sizeof s);
for(int i = 0;i < n;i ++){
for(int j = i+1;j < n;j ++){
for(int k = 0;k < n;k ++){
if(P[k].isOnLine(P[i], P[j]))
s[i][j] = s[j][i] |= (1 << k);
}
}
}
}
int dfs(int st){
if(dp[st] != 0x3f3f3f3f) return dp[st];
int cnt = 0;
for(int i = 0;i < n;i ++) if(st & (1 << i)) cnt++;
if(cnt == 0) return 0;
if(cnt <= 2) return dp[st] = 1;
for(int i = 0;i < n;i ++){
if(st & (1 << i)){
for(int j = i + 1;j < n;j ++){
if(st & (1 << j)){
dp[st] = min(dp[st], dfs(st - (st&s[i][j])) + 1);
}
}
break;
}
}
return dp[st];
}
int main(){
int t, CASE(0);
scanf("%d", &t);
while(t--){
scanf("%d", &n);
for(int i = 0;i < n;i ++) scanf("%d%d", &P[i].x, &P[i].y);
init();
printf("Case %d: %d\n", ++CASE, dfs((1 << n)-1));
}
return 0;
}