HDU5938 Four Operations

Four Operations

题目链接
【题目描述】
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4153 Accepted Submission(s): 1193

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’,长度5-20的字符串,将字符串分割成五个数字A,B,C,D,E,在五个数字之间按顺序加入符号+,-,*,/,即A+B-C*D/E,求最大的计算结果。
【思路】
只是个人看法。
按顺序,先算*/,再算±,所以C*D/E部分越小越好,C*D肯定是越小越好,这样就有两种情况,C*D>E或C*D<=E,如果C*D>E,则E需要变成两位数使得C*D/E最小,所以除数E只有可能是一位数或者两位数,C和D都是一位,剩下的A和B,需要组成尽可能大的数,只有可能是第一位加剩下的字符组成的数,或者最后一位加剩下的字符组成的数,取最大值,具体看图
在这里插入图片描述
【代码】

#include<string>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<math.h>
#include<minmax.h>
using namespace std;
int main() {
    
    
//	freopen("1.txt","r",stdin);
	int T;
	char s[30];
	scanf("%d",&T);
	for(int t=1; t<=T; t++) {
    
    
		scanf("%s",s);
		int len=strlen(s);
		//除数是一位时
		long long int sum=0;//位数较大,所以需要用long long int 
		long long int a,a1=0,a2=0,b,c,d;
		//求两种组合方式的最大值 
		for(int i=1; i<=len-4; i++) {
    
    
			a1=a1*10+int(s[i]-48);
		}
		a1+=int(s[0]-48);
		for(int i=0; i<len-4; i++) {
    
    
			a2=a2*10+int(s[i]-48);
		}
		a2+=int(s[len-4]-48);
		a=max(a1,a2);
		b=int(s[len-3]-48);
		c=int(s[len-2]-48);
		d=int(s[len-1]-48);
		sum=a-b*c/d;
		//除数是两位时
		if(len>5) {
    
    
			long long int sum2=0;
			a,a1=0,a2=0,b,c,d;
			for(int i=1; i<=len-5; i++) {
    
    
				a1=a1*10+int(s[i]-48);
			}
			a1+=int(s[0]-48);
			for(int i=0; i<len-5; i++) {
    
    
				a2=a2*10+int(s[i]-48);
			}
			a2+=int(s[len-5]-48);
			a=max(a1,a2);
			b=int(s[len-4]-48);
			c=int(s[len-3]-48);
			d=int(s[len-2]-48)*10+int(s[len-1]-48);
			sum2=a-b*c/d;
			sum=max(sum,sum2);
		}
		printf("Case #%d: %lld\n",t,sum);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/lmmmmmmmmmmmmmmm/article/details/89328445
今日推荐