跳到正文

题解

题解 P2915 【[USACO08NOV]奶牛混合起来Mixed Up Cows】

览遍千秋约 3 分钟
原文
文章信息与版本

文章信息

发布
2018年8月2日
收录
2026年8月20日
更新
2026年11月13日
篇幅
约 3 分钟
获赞
13
题目
P2915

版本

  1. v1当前

状压DP

观察奶牛的数据范围:4≤N≤164≤N≤16。

很明显,这是一道状压DP。

所以如果你不会位运算的话,可以右转出门了。


状态压缩

使用一个正整数tt来描述奶牛的选取情况,当tt的第rr位为11时,代表选取了该奶牛,反之亦然。


对整数tt的操作

假设我们要判断第rr头奶牛是否被选取,则当t&(1<<(r-1))为True时,表示选取了,反之亦然。


状态的表示

设opta,bopt_{a,b}代表在题目条件下,当前选取的奶牛序列的整数t=at=a时,且最后选取的奶牛为bb时的方案总数。


边界

opt1<<(e−1),e=1opt_{1<<(e-1),e}=1

1≤e≤N1≤e≤N


状态转移

枚举奶牛序列t=it=i,1≤i≤(1<<n)−11≤i≤(1<<n)-1

枚举当前序列的最后一只奶牛jj

当满足i&(1<<(j-1))为True时

枚举奶牛qq,当满足i∣(1<<(q−1))≠ii|(1<<(q-1))≠i且∣Sj−Sq∣>k|S_j-S_q|>k时,optq,(i∣(1<<(q−1)))=optq,(i∣(1<<(q−1)))+optj,iopt_{q,(i|(1<<(q-1)))}=opt_{q,(i|(1<<(q-1)))}+opt_{j,i}


代码:

C++
#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;
}
原文
存档评论11 条抓取于