HDU 5938 Four Operations(四则运算)
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 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.
小Ruins是个好学的男孩纸,最近他在学四则运算! 现在他打算练练四则运算。此处有个由数字'' - ''组成的字符串,依次添加'+', '-', '*' , '/'这四个运算符把字符串划分为5个部分,再算出结果(/ 使用整数除法)。 帮他找出可以获得的最大值吧!
CN
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
第一行为一个整数T,表示测试用例的数量。 每个测试用例为一个仅由数字 ''-'' 组成的字符串。 数据范围
<= T <= ^
<= 字符串长度 <=
CN
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.
对于每组测试用例,输出"Case #x: y",x表示从1开始的用例编号,y为结果。
CN
Sample Input - 输入样例
1
12345
Sample Output - 输出样例
Case #1: 1
题解
模拟水题。
一个只有5个部分,可以写成A+B-C*D/E
要使结果最大,则A+B最大,C*D/E最小
A+B最大,加号要么在第一位数后面,要么在最后一位数前面。
C*D/E最小,C和D都是1位数,E只有可能是1~3位数,到3位数的时候已经为0了。
所以最多只要就算三次即可,注意初始化。
代码 C++
#include <cstdio>
#include <cstring>
#include <algorithm>
#define ll __int64
char data[]; int main(){
int t, it, i, j, len;
ll opt, l, r, L, R, L10, R10;
for (it = scanf("%d ", &t); it <= t; ++it){
opt = (ll) << ;
gets(data); len = strlen(data);
L = ; L10 = ;
for (i = ; i < len - ; ++i, L10 *= ) L = L * + data[i] - '';
L10 /= ;
R = ; R10 = ;
j = std::min(, len - );
for (i = ; i <= j; ++i){
R = (data[len - i] - '')*R10 + R;
R10 *= ;
l = std::max(L / L10 + L % L10, L / + L % );
L10 /= ; L /= ;
r = (data[len - i - ] - '')*(data[len - i - ] - '') / R;
opt = std::max(opt, l - r);
}
printf("Case #%d: %I64d\n", it, opt);
}
return ;
}