poj3557(概率dp)

題意:給定n,p;表示n個點中任意兩點連邊的概率爲p,求生成的圖是個連通塊的概率。n<=20


解法:反向思考,ans[i]爲i個節點爲連通塊的概率,求ans[n]時候,求不爲一個連通塊的概率,然後用1減。求非連通時,枚舉與1號節點爲一個連通塊的點的個數即可。

公式:ans[i]=1.0-  sigma C[i-1][j-1]*ans[j]*pow(1.0-p,j*(i-j))  --- j from 1 to i-1;


代碼:

/******************************************************
* @author:xiefubao
*******************************************************/
#pragma comment(linker, "/STACK:102400000,102400000")
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <string.h>
//freopen ("in.txt" , "r" , stdin);
using namespace std;

#define eps 1e-8
#define zero(_) (abs(_)<=eps)
const double pi=acos(-1.0);
typedef long long LL;
const int Max=22;
const LL INF=0x3FFFFFFF;
double ans[23];
int n;
double p;
LL C[30][30];
void init()
{
    for(int i=0; i<Max; i++)
        for(int j=0; j<=i; j++)
            C[i][j]= j==0? 1 : C[i-1][j-1]+C[i-1][j];

}
int main()
{
    init();
    while(scanf("%d%lf",&n,&p)==2)
    {
       memset(ans,0,sizeof ans);
       ans[1]=1.0;
       for(int i=2;i<=n;i++)
       {
           double help=0;
           for(int j=1;j<i;j++)
           help+=C[i-1][j-1]*ans[j]*pow(1.0-p,double(j*(i-j)));
           ans[i]=1.0-help;
       }
       printf("%.3lf\n",ans[n]);
    }
    return 0;
}

發佈了217 篇原創文章 · 獲贊 10 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章