HDU-5938 Four Operations(字符串处理)

Four Operations

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 151    Accepted Submission(s): 61


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
1T105
5length of string20
 

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


题意:给你一个长度不超过20的字符串,让你将这个四个运算符依次序放入,使得最后结果最大。

思路:设结果为   a + b - c * d / div

c * d / div的结果要尽可能小,c和d都是个位数就好了,c*d肯定最多二位数,所以考虑div是取一位还是两位(为什么不取更多位呢,取得多了a+b就小了啊,最终几个也小了)。

a + b的结果肯定要取最大值,什么时候最大呢,一种可能是第一位数+剩下所有组成的数,第二种可能是最后一位+前面所有组成的数(这里仅仅说的“-”前面的字符串)。

依次取多种情况的最大值,这个div的处理还是不好弄的,但是参考别人的找到一个不错的做法

-- overload1997的代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<utility>
#include<map>
#define maxn 25
typedef long long LL;
using namespace std;
const int mod=1e9+7;;
char s[maxn];
int a[maxn];
LL getnum(int l,int r){
    LL ans=0;
    for(int i=l;i<=r;i++){
        ans=(ans*10)+a[i];
    }
    return ans;
}
int main(){
    int t;
    scanf("%d",&t);
    for(int tcase=1;tcase<=t;tcase++){
        scanf("%s",s);
        int len=strlen(s);
        for(int i=0;i<len;i++){
            a[i]=s[i]-'0';
        }
        LL ans=a[0]+getnum(1,len-4)-a[len-3]*a[len-2]/a[len-1];
        ans=max(ans,getnum(0,len-5)+a[len-4]-a[len-3]*a[len-2]/a[len-1]);
        if(len>5){
            int div=getnum(len-2,len-1);
            ans=max(ans,a[0]+getnum(1,len-5)-a[len-4]*a[len-3]/div);
            ans=max(ans,getnum(0,len-6)+a[len-5]-a[len-4]*a[len-3]/div);
        }
        printf("Case #%d: %lld\n",tcase,ans);
    }
}

还可以不断从前向后枚举字符串,不断找最大值,见点击打开链接等等


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值