HDU5938 Four Operations

6 篇文章 0 订阅
1 篇文章 0 订阅


Four Operations

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)


Problem Description
Little Ruins is a studious boy, recently he learned the four operations!

Now he want to use four operations to generate a number, he takes a string which only contains digits  '1' -  '9', and split it into  5  intervals and add the four operations  '+''-''*' and  '/' in order, then calculate the result(/ used as integer division).

Now please help him to get the largest result.
 

Input
First line contains an integer  T , which indicates the number of test cases.

Every test contains one line with a string only contains digits  '1'- '9'.

Limits
1T105
5length of string20
 

Output
For every test case, you should output  'Case #x: y', where  x indicates the case number and counts from  1 and  y is the result.
 

Sample Input
  
  
1 12345
 

Sample Output
  
  
Case #1: 1
 


题意:

给出一个长度不小于5且只含有1-9的字符串,将“+  -  *  /”四则运算符按照顺序插入字符串做成一个式子,使得式子的运算结果最大,求出最大值。



题解:

因为按照一定次序填入并且不用考虑0的情况,所以式子可以看成a-b的情况,其中a是由两个数字相加组成,比较容易求出最大值,b是由两个数相乘再除以一个数组成,所以要想使得b足够小,应该使相乘两个数足够小(只有一位),并且除数大(位数需要和前面的加法位数对应),枚举除号位置,求出最大值。



AC代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL tolong(string s){
    int len=s.size();
    LL ret=0;
    for(int i=0;i<len;i++)
        ret=ret*10+(s[i]-'0');
    return ret;
}
int div(string s){
    int len=s.size();
    int ret=(s[0]-'0')*(s[1]-'0');
    int tmp=0;
    for(int i=2;i<len;i++)tmp=tmp*10+(s[i]-'0');
    return ret/tmp;
}
LL add(string s){
    int len=s.size();
    LL tmp,ret1=s[0]-'0';
    LL ret2=ret1;
    for(int i=1;i<=len-2;i++)
        ret2*=10;
    tmp=tolong(s.substr(1));
    ret1+=tmp;
    tmp/=10;
    ret2=ret2+tmp+(s[len-1]-'0');
    return (ret1>ret2?ret1:ret2);
}
int main(){
    ios::sync_with_stdio(false);
    int t,cnt=0;string s;
    cin>>t;
    while(t--){
        cin>>s;
        int len=s.size();
        int tmp=0;
        LL ans=-9999999999;
        while(++tmp){
            if(len-tmp<4)break;
            if(tmp>=4)break;
            LL a,b;
            a=add(s.substr(0,len-2-tmp));
            b=div(s.substr(len-2-tmp));
            if(a-b>ans)ans=a-b;
        }
        cout<<"Case #"<<++cnt<<": "<<ans<<endl;
    }
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值