题目描述:
Eva is a third-grade elementary school student. She has just learned how to perform addition and subtraction of arbitrary-precision integers. Her homework is to evaluate some expressions. It is boring, so she decided to add a little trick to the homework. Eva wants to add some plus and minus signs to the expression to make its value as large as possible.
Input
The single line of the input file contains the original arithmetic expression. It contains only digits, plus (‘+’) and minus (‘-’) signs.
The original expression is correct, that is:
• numbers have no leading zeroes;
• there are no two consecutive signs;
• the last character of the expression is a digit.
The length of the original expression does not exceed 1000 characters.
Output
Output a single line — the original expression with some plus and minus signs added. Output expression must satisfy the same correctness constraints as the original one. Its value must be as large as possible.
Examples
input
10+20-30
-3-4-1
+10
output
10+20-3+0
-3-4-1
+10
题目分析:
有一个表达式,由’+’、’-‘和数字组成,现在要求你在数字之间加上’+’或’-‘,使得这个表达式的值最大。
保证这个表达式没有前导零,两个运算符之间必有数字,最后一个和第一个为数字。
其实在分析过题意之后你会发现,我们只有可能将某个被减去的数字拆分,将这个数中间添上加号,并且让这个加上的数最大并且保证没有前导零。
既然只有这么一种情况,那就模拟一下就可以完成。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
char s[1010];
int a[1010];//a数组表示在s这个字符串的某个位置是否加上'+'
int main()
{
// freopen("easy.in","r",stdin);
// freopen("easy.out","w",stdout);
while(cin>>s)
{
int len=strlen(s);
memset(a,0,sizeof(a));
for(int i=0; i<len; i++)
{
if (s[i]=='-')
{
if (s[i+2]!='-' && s[i+2]!='+' && s[i+2]!='\0') a[i+2]=1;//出现减号并且减号后的数字可以被拆分
for(int j=i+2; j<len; j++)//拆分出的数尽可能大
{
if (s[j]=='0') a[j]=1;
else if (s[j]>='1' && s[j]<='9' && s[j-1]=='0') {a[j]=1;break;}
else break;
}
}
}
for(int i=0; i<len; i++)
{
if (a[i]==1) printf("+");
printf("%c",s[i]);
}
printf("\n");
}
return 0;
}