B. Dreamoon and WiFi :calculate no. of ways : recursive solution (branch and bound )


http://codeforces.com/contest/476/problem/B

#include<bits/stdc++.h>
using namespace std;
string s1,s2;
int val=0,n;
int dp[15][15];
int solve(int s,int l,int f)
{
    int &ret=dp[s][l];
    if(s==l)
    {
        if(f==val)
            return 1;
        else
            return 0;
    }
   
    int ct=0;                                   ///number of ways in starting is 0
    if(s2[s]=='+')
        ct+=solve(s+1,l,f+1);
    if(s2[s]=='-')
        ct+=solve(s+1,l,f-1);
    if(s2[s]=='?')
        ct+=solve(s+1,l,f+1)+solve(s+1,l,f-1);
    return ret=ct;                              /// In the last return this value

}
int main()
{
    int i,j,k,l;
    double ans;
    cin>>s1>>s2;
    n=s1.size();
    for(i=0;i<n;i++)
    {
        if(s1[i]=='+')
            val++;
        else
            val--;
    }
    double xx=1;
    for(i=0;i<n;i++)
    {
       if(s2[i]=='?')
       xx*=2.0;

    }
    k=solve(0,s2.size(),0);
    //cout<<k<<endl;
    ans=double(k);
    if(k==0)
        printf("%.10lf\n",ans);
    else
        printf("%.10lf\n",(double)ans/xx);

    return 0;
}

Comments

Popular posts from this blog

A. Dreamoon and Stairs : minimum steps to reach : recursion solution.

Getting Started With MEAN App Development with AngularJs , ExpressJs , NodeJs and MongoDB.