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.
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
1≤T≤105
5≤length of string≤20
Every test contains one line with a string only contains digits '1'- '9'.
Limits
1≤T≤105
5≤length of string≤20
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;
}
}