# 【bzoj5004】开锁魔法II 组合数学+概率dp

#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 310
using namespace std;
int a[N] , c[N] , vis[N] , sum[N];
double fac[N] , f[N][N];
int main()
{
int T;
scanf("%d" , &T);
while(T -- )
{
memset(vis , 0 , sizeof(vis));
memset(f , 0 , sizeof(f));
f[0][0] = 1;
int n , m = 0 , p , i , j , k;
scanf("%d%d" , &n , &p);
for(i = 1 ; i <= n ; i ++ ) scanf("%d" , &a[i]) , fac[i] = fac[i - 1] + log(i);
for(i = 1 ; i <= n ; i ++ )
{
if(!vis[i])
{
c[++m] = 0;
for(j = i ; !vis[j] ; j = a[j])
vis[j] = 1 , c[m] ++ ;
}
}
sum[m + 1] = 0;
for(i = m ; i ; i -- ) sum[i] = sum[i + 1] + c[i];
for(i = 1 ; i <= m ; i ++ )
for(j = max(i - 1 , p - sum[i]) ; j < p && j <= n - sum[i] ; j ++ )
for(k = 1 ; k <= c[i] && j + k <= p ; k ++ )
f[i][j + k] += f[i - 1][j] * exp(fac[c[i]] + fac[sum[i] - c[i]] + fac[p - j] + fac[sum[i] - p + j] - fac[k] - fac[c[i] - k] - fac[p - j - k] - fac[sum[i] - c[i] - p + j + k] - fac[sum[i]]);
printf("%.9lf\n" , f[m][p]);
}
return 0;
}


|转载请注明 [原文链接][作者] ，谢谢！

posted @ 2018-04-05 19:43  GXZlegend  阅读(1822)  评论(0编辑  收藏  举报