您的位置:首页 > 其它

BZOJ 1231: [Usaco2008 Nov]mixup2 混乱的奶牛( dp )

2015-06-08 16:37 471 查看


状压dp

dp( x , S ) 表示最后一个是 x , 当前选的奶牛集合为 S , 则状态转移方程 :

dp( x , S ) = Σ dp( i , S - { i } ) ( i ∈ S , abs( h[ i ] - h[ x ] ) > k )

-------------------------------------------------------------------------------------------

#include<cstdio>#include<algorithm>#include<cstring>#include<iostream> #define rep( i , n ) for( int i = 0 ; i < n ; i++ )#define clr( x , c ) memset( x , c , sizeof( x ) ) using namespace std; typedef long long ll; const int maxn = 18; int n , k;int h[ maxn ];ll d[ maxn ][ 1 << maxn ]; ll dp( int x , int S ) { ll &ans = d[ x ][ S ]; if( ans != -1 ) return ans; ans = 0; rep( i , n ) if( ( S & ( 1 << i ) ) && abs( h[ i ] - h[ x ] ) > k ) ans += dp( i , S ^ ( 1 << x ) ); return ans; } int main() {// freopen( "test.in" , "r" , stdin ); cin >> n >> k; rep( i , n ) scanf( "%d" , h + i ); clr( d , -1 ); rep( i , n ) d[ i ][ 1 << i ] = 1; long long ans = 0; int all = ( 1 << n ) - 1; rep( i , n ) ans += dp( i , all ); cout << ans << "\n"; return 0;}

-------------------------------------------------------------------------------------------

1231: [Usaco2008 Nov]mixup2 混乱的奶牛

Time Limit: 10 Sec Memory Limit: 162 MB
Submit: 685 Solved: 383
[Submit][Status][Discuss]

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

Source

Gold
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: