B1231 [Usaco2008 Nov]mixup2 混乱的奶牛 状压dp

发现是状压dp,但是还是不会。。。之前都白学了,本蒟蒻怎么这么菜,怎么都学不会啊。。。

其实我位运算基础太差了,所以状压学的不好。

题干:

Description

混乱的奶牛 [Don Piele, 2007] Farmer John的N(4 <= N <= 16)头奶牛中的每一头都有一个唯一的编号S_i (1 <= S_i <= 25,000). 奶牛为她们的编号感到骄傲, 所以每一头奶牛都把她的编号刻在一个金牌上, 并且把金牌挂在她们宽大的脖子上.
奶牛们对在挤奶的时候被排成一支"混乱"的队伍非常反感. 如果一个队伍里任意两头相邻的奶牛的编号相差超过K (1 <= K <= 3400), 它就被称为是混乱的. 比如说,当N = 6, K = 1时, 1, 3, 5, 2, 6, 4 就是一支"混乱"的队伍, 但是 1, 3, 6, 5, 2, 4
不是(因为5和6只相差1). 那么, 有多少种能够使奶牛排成"混乱"的队伍的方案呢? Input * 第 1 行: 用空格隔开的两个整数N和K * 第 2..N+1 行: 第i+1行包含了一个用来表示第i头奶牛的编号的整数: S_i Output 第 1 行: 只有一个整数, 表示有多少种能够使奶牛排成"混乱"的队伍的方案. 答案保证是 一个在64位范围内的整数. Sample Input 4 1 3 4 2 1 Sample Output 2 输出解释: 两种方法分别是: 3 1 4 2 2 4 1 3 HINT

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<ctime>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
#define duke(i,a,n) for(int i = a;i <= n;i++)
#define lv(i,a,n) for(int i = a;i >= n;i--)
#define clean(a) memset(a,0,sizeof(a))
const int INF = 1 << 30;
typedef long long ll;
typedef double db;
template <class T>
void read(T &x)
{
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-') op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op) x = -x;
}
template <class T>
void write(T x)
{
    if(x < 0) putchar('-'), x = -x;
    if(x >= 10) write(x / 10);
    putchar('0' + x % 10);
}
int ms,n, k, a[20];
ll dp[70004][20];
int main()
{
    read(n);read(k);
    duke(i,1,n)
    {
        read(a[i]);
        dp[1 << (i - 1)][i] = 1;
    }
    int ms = (1 << n) - 1;
    duke(i,1,ms)
    {
        duke(j,1,n)
        {
            if(i & (1 << (j - 1))) //判断是否为0 
            {
                duke(p,1,n)
                {
                    if(p != j && (i & (1 << (p - 1))) && abs(a[p] - a[j]) > k)
                    dp[i][j] += dp[i ^ (1 << (j - 1))][p];
                }
            }
        }
    }
    ll ans = 0;
    duke(i,1,n)
    {
        ans += dp[ms][i];
    }
    write(ans);
    printf("
");
    return 0;
}
原文地址:https://www.cnblogs.com/DukeLv/p/9527102.html