容斥原理模板

hdu4336

容斥原理模板:dfs部分

//hdu4336
#include<bits/stdc++.h>
using namespace std;
#define out(x) cout<<#x<<": "<<x<<endl
const double eps(1e-8);
const int maxn=10100;
const long long maxint=-1u>>1;
const long long maxlong=maxint*maxint;
typedef long long lint;
int n;
double p[maxn],ans;

void init()
{
    for (int i=1; i<=n; i++)
        cin>>p[i];
}

void dfs(int x, int tot, double sum)
{
    if (x==n+1)
    {
        if (sum==0.0) return;//divide by zero is illegal
        if (tot&1)
            ans+=1/sum;
        else
            ans-=1/sum;
        return;
    }
    dfs(x+1,tot,sum);
    dfs(x+1,tot+1,sum+p[x]);
}    

void work()
{
    ans=0;
    dfs(1,0,0.0);
    printf("%.4f\n",ans);
}

int main()
{
    while(cin>>n)
    {
    init();
    work();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36386435/article/details/82532455
今日推荐