题目描述:
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
Source
2016年中国大学生程序设计竞赛(杭州)
题目分析:
给一个n个数字的序列,在中间按顺序添加’+’ ‘-’ ‘*’ ‘\’,使得这个式子的结果最大。
因为是按顺序加运算符,所以这个式子类型只有一个情况,a+b-c*d/e,那么要使得这个式子最大,a+b要尽可能大,也就是a和b的位数是个是一位,另一个尽可能大,c和d只有一位,e我本以为也是只有一位,但是样例111991就是不对的,所以我们只要找a和b,c和d依然是一位,剩下的给e就行了。
代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <string>
const int MAXN=25;
const int INF=0x3f3f3f3f;
typedef long long LL;
using namespace std;
int T;
char s[MAXN];
int num[MAXN];
LL f(int s,int e)
{
LL ret=0;
for(int i=s; i<=e; i++)
{
ret*=10;
ret+=num[i];
}
return ret;
}
int main()
{
scanf("%d",&T);
for(int cas=1; cas<=T; cas++)
{
scanf("%s",s);
int len=strlen(s);
LL ans=-INF;
for(int i=0; i<len; i++)
{
num[i+1]=s[i]-'0';
}
for(int i=2; i<=len-3; i++)
{
LL c,d,e;
LL add=max((f(1,i-1)+f(i,i)),(f(1,1)+f(2,i)));
c=num[i+1],d=num[i+2];
e=f(i+3,len);
//printf("%lld %lld %lld %lld\n",add,c,d,e);
ans=max(ans,add-c*d/e);
}
printf("Case #%d: %lld\n",cas,ans);
}
return 0;
}