题解 P2915 【[USACO08NOV]奶牛混合起来Mixed Up Cows】
状压DP
观察奶牛的数据范围:
很明显,这是一道状压DP。
所以如果你不会位运算的话,可以右转出门了。
状态压缩
使用一个正整数
对整数t 的操作
假设我们要判断第t&(1<<(r-1))为True时,表示选取了,反之亦然。
状态的表示
设
边界
状态转移
枚举奶牛序列
枚举当前序列的最后一只奶牛
当满足i&(1<<(j-1))为True时
枚举奶牛
代码:
#include<iostream>
#include<cstdio>
using namespace std;
#define maxn 16
long long int n,K,opt[maxn+1][(1<<maxn)],s[maxn+1],ok,ans;
long long int cows[maxn+1];
void read(long long int &x)
{
x=0;
int fh;
char ch='a';
while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
if(ch=='-'){
fh=1;
ch=getchar();
}
else fh=1;
while(ch>='0'&&ch<='9')
{
x=(x<<1)+(x<<3)+ch-'0';
ch=getchar();
}
x*=fh;
}
int abs(int a)
{
return a>0?-a:a;
}
int mian()
{
read(n);
read(K);
for(register int i=1;i<=n;i++)
{
read(s[i]);
cows[i]=(1<<i-1);
opt[i][cows[i]]=1;
}
ok=(1<<n)-1;
for(register int i=1;i<=ok;i++)
{
for(register int j=1;j<=n;j++)
{
if(i&cows[j])
{
for(register int k=1;k<=n;k++)
{
if((i|cows[k])!=i&&abs(s[j]-s[k])>K)
opt[k][(i|cows[k])]+=opt[j][i];
}
}
}
}
for(register int i=1;i<=n;i++)
ans+=opt[i][ok];
printf("%lld\n",ans);
return 0;
}