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是个好学的男孩纸,最近他在学四则运算! 现在他打算练练四则运算。此处有个由数字'1' - '9'组成的字符串,依次添加'+', '-', '*' , '/'这四个运算符把字符串划分为5个部分,再算出结果(/ 使用整数除法)。 帮他找出可以获得的最大值吧!
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,表示测试用例的数量。 每个测试用例为一个仅由数字 '1'-'9' 组成的字符串。 数据范围 1 <= T <= 10^5 5 <= 字符串长度 <= 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.
对于每组测试用例,输出"Case #x: y",x表示从1开始的用例编号,y为结果。
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++
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #define ll __int64 5 char data[25]; 6 7 int main(){ 8 int t, it, i, j, len; 9 ll opt, l, r, L, R, L10, R10; 10 for (it = scanf("%d ", &t); it <= t; ++it){ 11 opt = (ll)1 << 63; 12 gets(data); len = strlen(data); 13 L = 0; L10 = 1; 14 for (i = 0; i < len - 3; ++i, L10 *= 10) L = L * 10 + data[i] - '0'; 15 L10 /= 10; 16 R = 0; R10 = 1; 17 j = std::min(3, len - 4); 18 for (i = 1; i <= j; ++i){ 19 R = (data[len - i] - '0')*R10 + R; 20 R10 *= 10; 21 l = std::max(L / L10 + L % L10, L / 10 + L % 10); 22 L10 /= 10; L /= 10; 23 r = (data[len - i - 2] - '0')*(data[len - i - 1] - '0') / R; 24 opt = std::max(opt, l - r); 25 } 26 printf("Case #%d: %I64d ", it, opt); 27 } 28 return 0; 29 }