洛谷 2915 [USACO08NOV]奶牛混合起来Mixed Up Cows

一道水状压,然而不知道是不是太久没做过dp了,我盯着它二十分钟才反应过来。。。。

还把数组开小了WA了一发QAQ

//Twenty
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<vector>
#include<cmath>
#include<queue>
#include<ctime>
const int maxn=(1<<16)+2;
typedef long long LL;
using namespace std;
int n,kk,nn,cnt[maxn],id[17];
LL dp[2][maxn][16];

namespace fastIO {
    const int sz=1<<15|1;
    char ch,buf[sz],*l,*r;
    void gechar(char &c) {
	    if(l==r) r=(l=buf)+fread(buf,1,sz,stdin);
	    c = l==r?(char)EOF:*l++;
	}
	template<typename T> void read(T &x) {
	    int f=1; x=0; gechar(ch);
	    while(ch!='-'&&(ch<'0'||ch>'9')) gechar(ch);
	    if(ch=='-') f=-1,gechar(ch);
	    for(;ch>='0'&&ch<='9';gechar(ch)) x=x*10+ch-'0'; x*=f;
	}
}

void pre() {
	nn=(1<<n)-1;
    for(int i=0;i<=nn;i++) {
    	int tp=i;
    	while(tp) {
			cnt[i]++;
			tp-=(tp&(-tp));
		}
	}
}

void work() {
	int o=0;
	dp[o][0][0]=1;
	id[0]=1e9;
	LL ans=0;
	for(int i=1;i<=n;i++) {
		o^=1;
		for(int j=1;j<=nn;j++) if(cnt[j]==i) {
			for(int k=1;k<=n;k++) {
				int fl=0;
				if(j&(1<<k-1)) {
					int pr=j^(1<<k-1);
					for(int l=(i!=1);l<=n;l++) 
					    if(dp[o^1][pr][l]&&abs(id[l]-id[k])>kk) {
						if(fl==0) {
							dp[o][j][k]=dp[o^1][pr][l];
							fl=1;
						}
						else dp[o][j][k]+=dp[o^1][pr][l];
					}	
				}
				if(!fl) dp[o][j][k]=0;
				if(i==n) 
					ans+=dp[o][j][k];
			}
		}
	}
	printf("%lld
",ans);
}

void init() {
	fastIO::read(n);
	fastIO::read(kk);
	for(int i=1;i<=n;i++) fastIO::read(id[i]);
}

//#define DEBUG
int main()  {
#ifdef DEBUG
    freopen("1.in","r",stdin);
    //freopen(".out","w",stdout);
#endif
    init();
    pre();
    work();
    return 0;
}
原文地址:https://www.cnblogs.com/Achenchen/p/7744920.html