HDU 5938 Four Operations(思维)

针对给定的数字字符串,通过合理插入四则运算符来最大化最终的计算结果。本篇介绍了一种有效的枚举策略,仅需考虑特定情况即可得出最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Source
2016年中国大学生程序设计竞赛(杭州)

题意:给你一个字符串,你依次放入+,-,*,/,按照顺序的,使得最后的结果最大

思路:
直接枚举减号的位置就行,然后字符串就分成了两部分,左边的加号,必须是有一个是一位数,所以加号位置只有两种可能,即最左边和最右边,对于右半部分,乘号两侧也应该是1位数,所以也可以直接得到。

看了其他的博客,发现,不用枚举减号,只有两种可能,除号后面为1位数或者是两位数,所以只需要枚举两种可能就行。

枚举减号代码如下:

#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
char str[100];
ll Get(int l,int r){
    ll res = 0;
    for(int i=l;i<=r;++i)
        res = res*10 + (str[i] - '0');
    return res;
}
ll solve(){
    int len = strlen(str);
    ll Max = -123456789123;
    ll a,b,c,d,e;
    for(int Mid=1;Mid<len-3;++Mid){
        a = str[0] - '0';
        b = str[Mid] - '0';
        a += Get(1,Mid);
        b += Get(0,Mid-1);
        ll res = max(a,b);
        c = str[Mid+1] - '0';
        d = str[Mid+2] - '0';
        e = Get(Mid+3,len-1);
        Max = max(Max,res-c*d/e);
    }
    return Max;
}
int main(void){

    int T,Case = 0;
    scanf("%d",&T);
    while(T--){
        scanf("%s",str);
        printf("Case #%d: %lld\n",++Case,solve());
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值