BZOJ 1226 学校食堂(状压DP)

时间:2024-07-18 09:37:44

状压DP

f(i,j,k)表示前i−1个人已经吃了饭,且在i之后的状态为j的人也吃了饭(用二进制表示后面的状态),最后吃的那个人是i之后的第k个 
(注意k可以是负数) 
然后 
如果j&1=1那么就表明第i个人也是吃了的,所以可以转移到f(i+1,j>>1,k−1) 
否则就枚举下一个吃饭的人,转移到f(i,j+1<<l,l) 
这么看也不是很难吧哈。。

# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi acos(-1.0)
# define eps 1e-
# define MOD
# define INF
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<,l,mid
# define rch p<<|,mid+,r
//# define mp make_pair
# define pb push_back
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
int x=,f=;char ch=getchar();
while(ch<''||ch>''){if(ch=='-')f=-;ch=getchar();}
while(ch>=''&&ch<=''){x=x*+ch-'';ch=getchar();}
return x*f;
}
void Out(int a) {
if(a<) {putchar('-'); a=-a;}
if(a>=) Out(a/);
putchar(a%+'');
}
const int N=;
//Code begin... struct Node{int t, b;}node[N];
int dp[N][<<][]; int main ()
{
int T, n;
scanf("%d",&T);
while (T--) {
scanf("%d",&n); FO(i,,N) FO(j,,<<) FO(k,,) dp[i][j][k]=INF;
FOR(i,,n) scanf("%d%d",&node[i].t,&node[i].b);
int mi=INF;
FOR(i,,n) {
--mi;
if (mi<) break;
mi=min(mi,node[i].b);
dp[][<<(i-)][(i-)+]=;
}
FOR(i,,n) FO(j,,<<) FOR(k,,) {
if (dp[i][j][k]==INF) continue;
if (j&) dp[i+][j>>][k-]=min(dp[i+][j>>][k-],dp[i][j][k]);
else {
mi=INF;
FOR(l,i,n) {
--mi;
if (mi<) break;
if ((j&(<<(l-i)))==) {
dp[i][j|(<<(l-i))][l-i+]=min(dp[i][j|(<<(l-i))][l-i+],dp[i][j][k]+(node[l].t^node[i+k-].t));
mi=min(mi,node[l].b);
}
}
}
}
int ans=INF;
FOR(i,,) ans=min(ans,dp[n+][][i]);
printf("%d\n",ans);
}
return ;
}