Yet another A + B
一、原文
time limit per test : 0.25 s
memory limit per test : 64 MB
input : standard input
output : standard output
You are given three numbers. Is there a way to replace variables A, B and C with these numbers so the equality A + B = C is correct?
Input
There are three numbers X1, X2 and X3 (1 ≤ Xi ≤ 10100), each on a separate line of input.
Output
Output either “YES”, if there is a way to substitute variables A, B and C with given numbers so the equality is correct, or “NO” otherwise.
Examples
input
1 2 3
output
YES
input
1 2 4
output
YES
input
1 3 5
output
NO
二、分析(收获)
1)本题为大数据加法,建议字符数组,利用strcmp好比较。当然结构体和string也是可以的。
2)利用DFS来巧妙处理组合问题。
3)细节上:1、对大数逆置,低位在前利于后续加法和比较
2、通过预处理(比较大小、处理前置0)和*char来传递数组
3、对于最高仍然有进位需要单独处理
三、代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define Max 105
using namespace std;
int flag = 0;
char s[3][Max],ans[3][Max];
char s1[Max],s2[Max];
char *add(char *x,char *y)
{
if(strlen(x) < strlen(y))
{
strcpy(s1,y);
strcpy(s2,x);
}
else
{
strcpy(s1,x);
strcpy(s2,y);
}
int d = 0,i = 0;
for(i = 0;i < strlen(s2);i ++)
{
d += s1[i] - '0' + s2[i] - '0';
s1[i] = d % 10 + '0';
d /= 10;
}
while(s1[i])
{
d += s1[i] - '0';
s1[i ++] = d % 10 + '0';
d /= 10;
}
if(d)
{
s1[i ++] = d % 10 + '0';
d /= 10;
s1[i] = '\0';
}
return s1;
}
void dfs(int k)
{
if(flag)return ;
if(k == 3)
{
if(strcmp(add(ans[0],ans[1]),ans[2]) == 0)flag = 1;
return ;
}
for(int i = 0;i < 3;i ++)
{
strcpy(ans[k],s[i]);
dfs(k + 1);
}
}
int main()
{
for(int i = 0;i < 3;i ++)
{
cin>>s[i];
reverse(s[i],s[i] + strlen(s[i]));
//由于可能有前置0,需要专门处理;
for(int j = strlen(s[i]);j >= 1;j --)
{
if(s[i][j - 1] != '0')
{
s[i][j] = '\0';
break;
}
}
}
dfs(0);
if(flag)cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}