hdu - 2266 How Many Equations Can You Find (简单dfs)

http://acm.hdu.edu.cn/showproblem.php?pid=2266

给一个字符串和一个数n,在字符串中间可以插入+或者 -,问有多少种等于n的情况.

要注意任意两个数之间都可以插入也可以不插入,注意枚举完所有情况.

#include <cstdio>
#include <cstring>
char s[15];
int n,l,cnt;

void dfs(int k,int sum)
{
    if(k==l)
    {
        if(sum==n) cnt++;
        return;
    }
    long long ans=0;
    for(int i=k;i<l;i++)
    {
        ans=ans*10+s[i]-'0';
        dfs(i+1,sum+ans);
        if(k!=0) dfs(i+1,sum-ans);
    }
}
int main()
{
    //freopen("a.txt","r",stdin);
    while(~scanf("%s",s))
    {
        scanf("%d",&n);
        //printf("%s %d\n",s,n);
        l=strlen(s);
        cnt=0;
        dfs(0,0);
        printf("%d\n",cnt);
    }
    return 0;
}

 

posted @ 2015-06-01 20:22  NowAndForever  阅读(151)  评论(0编辑  收藏  举报