2015-2016ACM-ICPC NEER northern-subregional-contest E Easy Arithmetic 思维、模拟

题目描述:

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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值