[HDU 4336]Card Collector

· · 个人记录

题目

        点这里看题目。

分析

        看到N\le 20,嗯,状压。
        定义状态:
        DP(S):当前拥有的牌的集合为S的时候,得到全部的牌还需要的期望步数。
        状态转移不难看出:
        \displaystyle DP(S)=\sum_{u\not\in S}p_uDP(S\cup u)+(1-\sum_{u\not\in S}p_u)DP(S)+1
        移项之后就可以愉快地转移了。

代码

#include <cstdio>

const int MAXN = 25, MAXSIZ = ( 1 << 20 ) + 5;

template<typename _T>
void read( _T &x )
{
    x = 0;char s = getchar();int f = 1;
    while( s > '9' || s < '0' ){if( s == '-' ) f = -1; s = getchar();}
    while( s >= '0' && s <= '9' ){x = ( x << 3 ) + ( x << 1 ) + ( s - '0' ), s = getchar();}
    x *= f;
}

template<typename _T>
void write( _T x )
{
    if( x < 0 ){ putchar( '-' ); x = ( ~ x ) + 1; }
    if( 9 < x ){ write( x / 10 ); }
    putchar( x % 10 + '0' );
}

double f[MAXSIZ];
double p[MAXN];
int N;

int main()
{
    int maxS;
    while( ~ scanf( "%d", &N ) )
    {
        for( int i = 1 ; i <= N ; i ++ ) scanf( "%lf", &p[i] );
        maxS = 1 << N;
        f[maxS - 1] = 0;
        for( int S = maxS - 2 ; ~ S ; S -- )
        {
            double coe = 0;
            f[S] = 1;
            for( int j = 1 ; j <= N ; j ++ )
            {
                if( ! ( S & ( 1 << ( j - 1 ) ) ) )
                {
                    coe += p[j];
                    f[S] += p[j] * f[S | ( 1 << ( j - 1 ) )];
                }
            }
            f[S] /= coe;
        }
        printf( "%.12lf\n", f[0] );
    }
    return 0;
}