当前位置:编程学习 > C/C++ >>

10317 - Equating Equations

/*

   一个搜索题 需要剪枝    把等式 a+b=c+d 转化为 a+b-c-d 这种形式   算出所有数值之和  如果不为偶数 则直接输出no

先计算出加号的数量 lp 也就是lp+1个数相加  进行搜索

 dfs需要进行几层剪枝: 如果当前tsum《=sum/2 则进行下一层搜索

*/

#include<cstdio>

#include<cstring>
#include<cstdlib>


char s[11000],oper[1100];
int num[1100],a[1100],b[1010],vis[1100];
int sum,lp,ln,po;
int change()
{
    int l = strlen(s);
    ln=0;
    sscanf(s,"%d",&num[ln++]);
    sum = num[0];
    for(int i = 1; i < l; i++)
    {
        if(s[i]=='='||s[i]=='-'||s[i]=='+')
        {
            if(s[i]=='=') po = ln;
            oper[ln] = s[i];
            sscanf(s+i+1,"%d",&num[ln]);
            sum += num[ln++];
        }
    }
    lp=1;
    for(int i = 1; i < ln; i++)
        if(i<po&&oper[i]=='+')
            lp++;
        else if(i>po&&oper[i]=='-')
            lp++;
}
int dfs(int cur,int pos,int tsum)
{
    if(lp-cur>ln-pos)
        return 0;
    if(cur==lp)
    {
        if(tsum*2==sum)
            return 1;
        return 0;
    }
    if(pos<ln)
    {
        if((tsum+num[pos])*2<=sum)
        {
            vis[pos]=1;
            b[cur] = num[pos];
            if(dfs(cur+1,pos+1,tsum+num[pos]))
                return 1;
        }
    }
    vis[pos]=0;
    if(pos<ln&&dfs(cur,pos+1,tsum))
        return 1;
    return 0;
}


int main()
{
    while(gets(s))
    {
        memset(vis,0,sizeof(vis));
        change();
        if(sum%2==0&&dfs(0,0,0))
        {
            int la=1;
            a[0] = b[0];
            for(int i = 1; i < ln; i++)
            {
                if(i<po&&oper[i]=='+')
                    a[i] = b[la++];
                else if(i>po&&oper[i]=='-')
                    a[i] = b[la++];
            }
            int k=1;
            for(int i = 0; i < ln; i++)
                if(!vis[i])
                {
                    while(k<po && oper[k]=='+' && k<ln) ++k;
                    while(k>po && oper[k]=='-' && k<ln) ++k;
                    a[k++] = num[i];
                }
            printf("%d",a[0]);
            for(int i = 1; i < ln; i++)
            printf(" %c %d",oper[i],a[i]);
            printf("\n");
        }
        else
            puts("no solution");
    }
    return 0;
}
 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,