codefroces 482C Game with Strings (概率dp神题)

题意:

给出n个字符串,选择每个字符串的概率等同都是1/n,每个字符串的长度相同。现在要玩一个游戏,就是A去任意藏起来一个字符串,B通过询问这个字符串的某个位置是什么字符,然后来判断这个字符串是什么。问:询问问题的数量的期望是多少。

题解:

一看题目,无法下手,堪称神题啊。

大牛正解:dp[s]表示状态为s的时候到问出这个字符串是什么还需要的概率,s中存的是问题。p[i]表示询问了i个问题就能得出是什么字符串的概率,最后是求出sum{p[i]*i}即可。

首先预处理出can[s],can[s]表示状态s时能区分的字符串个数。预处理也是有技巧的,否则TL。

任意枚举两个串不能相同部位,然后相同的部分状压成S,那么cannot[S]|=(1<<i)|(1<<j)对应s的时候不能区分的串的状态。最后状态full递推到0,求出can[s]。

dp的时候dp存的是不能区分这些字符串的概率,p[i]表示之前说过了,那么正好通过dp不区分,p区分,然后相互排序组合(语言不好描述),相当于1区分2不区分、1不区分2区分、1区分2区分、1不区分2不区分。因为我们知道状态压缩是可以做到像这样的排列组合的。

#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#include<map>
using namespace std;
typedef long long ll;
const int oo=0x3f3f3f3f;
const ll OO=1LL<<61;
const int MOD=10007;
const int maxn=55;
double dp[(1<<20)+5],p[maxn];
char str[maxn][22];
ll can[(1<<20)+5],cannot[(1<<20)+5];
int n,len,full;

int bitcount(ll st)
{
    return st==0 ? 0 : bitcount(st>>1)+(st&1);
}

void Init()
{
    memset(cannot,0,sizeof cannot);
    memset(can,0,sizeof can);
    for(int i=0;i<n;i++)
    {
        for(int j=i+1;j<n;j++)
        {
            int s=0;
            for(int k=0;k<len;k++)
                s|=(str[i][k]==str[j][k])<<k;
            cannot[s]|=(1LL<<i)|(1LL<<j);
        }
    }
    for(int s=full;s;s--)
    {
        for(int i=0;i<len;i++)
        {
            if(s&(1<<i))
                cannot[s^(1<<i)]|=cannot[s];
        }
        can[s]=n-bitcount(cannot[s]);
    }
}

void Dp()
{
    memset(dp,0,sizeof dp);
    memset(p,0,sizeof p);
    dp[0]=1.0;
    for(int s=0;s<=full;s++)
    {
        int qcnt=bitcount(s);///问的问题数
        int sum=n-can[s];///这个状态对应的不能区分的字符串个数
        double p1=dp[s]/(len-qcnt);///剩下的位置,询问某个位置的概率
        if(can[s]==n)continue;
        for(int i=0;i<len;i++)///询问的问题
        {
            if(s&(1<<i))continue;
            int st=s|(1<<i);
            double p2=1.0*(can[st]-can[s])/sum;///区分can[st]-can[s]这些字符串的概率
            dp[st]+=p1*(1-p2);///询问了qcnt+1个位置不区分这些字符串的概率
            p[qcnt+1]+=p1*p2;///询问了qcnt+1个位置把字符串区分了的概率
        }
    }
}

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0;i<n;i++)
            scanf("%s",str[i]);
        len=strlen(str[0]);
        full=(1<<len)-1;
        Init();
        Dp();
        double ans=0;
        for(int i=1;i<=len;i++)
            ans+=p[i]*i;
        if(n==1)
            ans=0.0;///一个字符串当然不用猜了,直接能找到
        printf("%.15lf\n",ans);
    }
    return 0;
}
/**
2
aab
aac
3
aaA
aBa
Caa
3
aca
vac
wqq

*/








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值