CodeForces 58 E.Expression(dfs)

Description

给出一个表达式 a + b = c ,要求找到一个等号成立且长度最短的表达式 x + y = z 使得 a , b , c 分别是 x , y , z 的子序列

Input

输入一个表达式 a + b = c ( 1 a , b , c 10 6 )

Output

输出满足条件的表达式 x + y = z

Sample Input

2+4=5

Sample Output

21+4=25

Solution

暴搜,从最低位开始,记录进位,如果当前位满足条件则不需要多加数字,否则分别考虑从这三个数的对应位置加数字(使得当前位满足条件)

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
int X,Y,L;
int Len(ll x)
{
    int len=0;
    while(x)x/=10,len++;
    return len;
} 
ll Val(ll x,int m)
{
    while(m--)x*=10;
    return x;
}
void dfs(int a,int b,int c,int x,int y,int add,int len,int m)
{
    if(len>=L)return ;
    if(!a&&!b&&!c&&!add)
    {
        X=x,Y=y,L=len;
        return ;
    }
    if(!c)
    {
        dfs(0,0,0,x+Val(a,m),y+Val(b,m),0,len+Len(a+b+add),m);
        return ;
    }
    if((a%10+b%10+add)%10==c%10)
        dfs(a/10,b/10,c/10,x+Val(a%10,m),y+Val(b%10,m),(a%10+b%10+add-c%10)/10,len,m+1);
    if(a%10!=(c-b%10-add+10)%10)
        dfs(a*10+(c-b%10-add+10)%10,b,c,x,y,add,len+1,m);
    if(b%10!=(c-a%10-add+10)%10)
        dfs(a,b*10+(c-a%10-add+10)%10,c,x,y,add,len+1,m);
    if(c%10!=(a%10+b%10+add)%10)
        dfs(a,b,c*10+(a%10+b%10+add)%10,x,y,add,len+1,m);
    return ;
}
int main()
{
    ll a,b,c;
    char s;
    cin>>a>>s>>b>>s>>c;
    L=15;
    dfs(a,b,c,0,0,0,0,0);
    cout<<X<<"+"<<Y<<"="<<X+Y<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/v5zsq/article/details/81040826
58