Luogu2915 [USACO08NOV]奶牛混合起来Mixed Up Cows (状压DP)

枚举末位状态

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long

#define ON_DEBUG

#ifdef ON_DEBUG

#define D_e_Line printf("

----------

")
#define D_e(x)  cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("inn.txt","r",stdin);

#else

#define D_e_Line ;
#define D_e(x)  ;
#define Pause() ;
#define FileOpen() ;

#endif

struct ios{
    template<typename ATP>ios& operator >> (ATP &x){
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x*= f;
        return *this;
    }
}io;
using namespace std;

const int N = 16;

int a[17];
long long f[16][1<<16];

int main(){
	FileOpen();
	int n, D;
	io >> n >> D;
    R(i,0,n - 1){
    	io >> a[i];
    	f[i][1 << i] = 1;
    }
    R(i,0,(1 << n) - 1){
    	R(j,0,n - 1){
    		if(i & (1 << j)){
    			R(k,0,n - 1){
    				if(!(i & (1 << k)) && Abs(a[j] - a[k]) > D){
    					int m = i | (1 << k);
    					f[k][m] += f[j][i];
    				}
    			}
    		}
    	}
    }
    
    int ans = 0;
	R(i,0,n - 1)
        ans += f[i][(1<<n)-1];
        
    printf("%lld",ans);
	return 0;
}

原文地址:https://www.cnblogs.com/bingoyes/p/11234777.html