问题描述:
解决方案:
#include <iostream>
#include <cstdio>
#include <cstring>
int getLength(char*top,char*bottom)
{
int len1 = 205,len2 = 205;
int b_index = 0;
int p;
while(bottom[b_index])
{
p = 0;
while(bottom[b_index + p] && top[p])
{
if(bottom[b_index + p] - '0' + top[p] > '3')
break;
p++;
}
if(!bottom[b_index + p] || !top[p])
break;
b_index++;
}
if(!top[p])
len1 = strlen(bottom);
if(!bottom[b_index])
len1 = strlen(bottom) + strlen(top);
if(p && !bottom[b_index + p])
len1 = strlen(bottom) + strlen(top) - p;
p = 0;
int top_len = strlen(top);
b_index = top_len - 1;
while(b_index >= 0)
{
p = 0;
while(b_index - p >=0 && top_len - p -1 >= 0)
{
if(bottom[b_index - p] - '0' + top[top_len - p - 1] > '3')
break;
p++;
}
if(b_index - p < 0 || top_len - p < 0)
break;
b_index--;
}
if(top_len - p - 1 < 0)
len2 = strlen(bottom) - strlen(top);
if(b_index < 0)
len2 = strlen(bottom) + strlen(top);
if(p && b_index - p < 0)
len2 = strlen(bottom) + strlen(top) - p;
return len1 > len2?len2:len1;
}
int main()
{
char bottom[105],top[105];
while(scanf("%s",bottom) != EOF){
scanf("%s",top);
int length;
if(strlen(bottom) < strlen(top))
length = getLength(bottom,top);
else
length = getLength(top,bottom);
printf("%d\n",length);
}
return 0;
}
核心思路:总是将长的作为底考虑,分为两种情况讨论,1.短边从右边出头 2.短边从左边出头,其他情况与任意一种合并即可(能够合并,不能合并)。