Four Operations
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4690 Accepted Submission(s): 1349
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
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
题目大意:
给你一个由1-9数字组成的数字串,让你将其分成五个数(不能打乱顺序)(不能为空),然后使得其五个数之间用+-*/(有序)四个符号链接起来,使得运算结果最大。
样例分析:
1+2-3*4/5=1
分析:
贪心求解
AC代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#define ll long long
using namespace std;
int a[50];
char s[50];
ll getnum(int l,int r) {
ll ans = 0;
for(int i=l;i<=r;i++)
ans = ans*10+a[i];
return ans;
}
int main() {
int T;
int cnt=1;
cin >> T;
while(T--) {
scanf("%s",s);
ll num;
int len=strlen(s);
for(int i=0;i<len;i++)
a[i]=s[i]-'0'; //将字符串转化为数字
//div为一位数的情况
num = a[0]+getnum(1,len-4)-a[len-3]*a[len-2]/a[len-1];
num = max(num,getnum(0,len-5)+a[len-4]-a[len-3]*a[len-2]/a[len-1] ) ;
//div为两位数的情况
if(len>5) {
int div = getnum(len-2,len-1);
num=max(num,a[0]+getnum(1,len-5)-a[len-4]*a[len-3]/div);
num=max(num,getnum(0,len-6)+a[len-5]-a[len-4]*a[len-3]/div);
}
cout<<"Case #"<<cnt<<": "<< num<<endl;
cnt++;
}
return 0;
}