hdu5938 Four Operations(贪心)

本文介绍了一道编程题——通过四则运算求字符串组成的数字串所能产生的最大整数值。文章详细解析了如何通过遍历特定符号位置来解决此问题,并提供了一段完整的C++代码实现。

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

Four Operations

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


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

为了满足条件乘号左右肯定是只有一个数,只要遍历除号的位置,定下了除号,那么减号,乘号,除号都已经确定,加号只可能在剩下的可放入的地方的最前或最后,取这些可能中的最大值即可。

#include<iostream>
#include<cmath>
#include<string.h>
using namespace std;
char num[33];
long long nn[33];
long long len;
long long _max;
long long run(long long p1,long long p2)
{
    long long anss=0;
    long long res=1;
    for(int i=p2-1;i>=p1;i--)
    {
        anss+=nn[i]*res;
        res*=10;
    }
    return anss;
}
void cal(long long a,long long b,long long c,long long d)
{
    long long div=run(a,len);
    long long chen=run(b,a);
    long long jian=run(c,b);
    long long jia=run(d,c);
    long long x=run(0,d);
    long long aa=x+jia-jian*chen/div;
    //cout<<x<<" "<<jia<<' '<<jian<<' '<<chen<<' '<<div<<endl;
    if(aa>_max)
    {
        _max=aa;
    }
}
int main()
{
    int cas;
    scanf("%d",&cas);
    long long cc=0;
    while(cas--)
    {
        _max=-100000;
        scanf("%s",&num);
        len=strlen(num);
        for(int i=0;i<len;i++)
        {
            nn[i]=num[i]-'0';
        }
        for(int i=len-1;i>=4;i--)
        {
           cal(i,i-1,i-2,1);
           cal(i,i-1,i-2,i-3);
        }
        printf("Case #%lld: %lld\n",++cc,_max);
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值