HDU 5938 Four Operations 【字符串处理,枚举,把数字字符串变为数值】

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


12345

Sample Output

Case #1: 1


【题意】:给一个字符串,按+, -, *, /的顺序插入将字符串分成a+b-c*d/e,要求结果最大。
【分析】:枚举负号的位置,因为要使整个值最大,C*D应该最小,所以C和D都只取一位。
A+B的值最大需要使A或B的位数尽可能大,即A一位,B为到负号前的所有位或者B为符号前一位,
A为开头到负号前一位位置,两种情况取最大值。由于C和D都确定了E也随之确定了。
所以总的来说就是枚举一下负号的位置,然后判断一下A+B的最大值就可以了。 
【代码】:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <string>

const int maxn=25;
const int inf=0x3f3f3f3f;
typedef long long ll;
using namespace std;

char a[maxn];
int num[maxn];

ll f(int s,int e)
{
    ll res=0;
    for(int i=s; i<=e; i++)
    {
        res = res*10 + num[i] ;
    }
    return res;
}//
int main()
{
    int t;
    scanf("%d",&t);
    for(int cas=1;cas<=t;cas++)
    {
        scanf("%s",a);
        int len=strlen(a);
        ll ans = -inf;
        
        for(int i=0;i<len;i++)
        {
            num[i+1]=a[i]-'0';
        }
        
        for(int i=2;i<=len-3;i++)
        {
            ll add,c,d,e;
            
            add=max((f(1,i-1)+f(i,i)) , (f(1,1)+f(2,i)));
            c=num[i+1];
            d=num[i+2];
            e=f(i+3,len);

            ans=max(ans,add-c*d/e);
        }
        printf("Case #%d: %lld\n",cas,ans);
    }
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/Roni-i/p/7505345.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值