交了八次才过,太煎熬了…在这个题上肝了一个多小时…
还是太菜了,因为一些细节而浪费了很多时间.
题目链接
题目
Little Ruins is a studious boy, recently he learned the four operations!
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).
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≤20Now please help him to get the largest result.
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.
因个人能力有限只会暴力做这道题,思路就是计算减号前的所有情况中的最大值,和减号之后所有情况中的最小值,取其差的最大值.比较麻烦点的就是算出所有减号前两数相加的情况和减号后a*b/c的情况.
一开始因为将ans设为-1(没有足够小),一直wa,也没发现这有错,后来拿自己qq号做样例输入一下试了试,发现输出的最大值应该是-7,但结果是-1,于是就发现了这个小bug,于是就ac了hhh.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define ll long long
using namespace std;
const int maxn = 1e5+10;
const ll inf = 9223372036854775800;
ll cal(char str[],int l,int r)
{
ll a=0,base=1;
for(int i=r; i>=l; i--)
{
a+=(str[i]-'0')*base;
base*=10;
}
return a;
}
int main()
{
char str[25];
int t;
scanf("%d",&t);
for(int C=1; C<=t; C++)
{
scanf("%s",str);
int n = strlen(str);
ll ans = -inf;
ll a,b,c,d,e;
for(int i=n-4; i>=1; i--)
{
ll L=-1,R=inf;
for(int j=0; j<i; j++)
{
a = cal(str,0,j);
b = cal(str,j+1,i);
L=max(L,a+b);
}
for(int j=n-3; j>=i+1; j--)
{
for(int k=j+1; k<=n-2; k++)
{
c = cal(str,i+1,j);
d = cal(str,j+1,k);
e = cal(str,k+1,n-1);
R=min(R,c*d/e);
}
}
ans=max(ans,L-R);
}
printf("Case #%d: %lld\n",C,ans);
}
return 0;
}