HDU5938 Four Operations


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
using namespace std;
typedef long long LL;
LL tolong(string s){
    int len=s.size();
    LL ret=0;
    for(int i=0;iret2?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<<": "<



你可能感兴趣的:(题解,HDU,字符串)