(2016年中国大学生程序设计竞赛(杭州)) HDU 5938 Four Operations 思维题 + 枚举

41 篇文章 0 订阅
14 篇文章 0 订阅

(HDU 5938)Four Operations

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

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

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

题目大意:
给你一个由1-9数字组成的数字串,让你将其分成五个数(不能打乱顺序)(不能为空),然后使得其五个数之间用+-*/四个符号链接起来,使得运算结果最大。
样例分析:
1+2-3*4/5=1

思路:

1、首先我们设定这五个数为a,b,c,d,e,那么其结果为:a+b-c*d/e,我们分析发现,其拆分出来的数c,d,e都是正数,那么-c*d/e一定是一个负数,那么我们第一个任务就是将其值尽可能的缩小,并且让a+b尽可能的大。

2、我们首先来分析如何让a+b尽可能的大,现在我们将问题简化,给你一个字符串,让你将其分成两个数之后求和,使其最大,那么我们一定想要将一个数设定为当前字符串长度-1的一个长度的数,另一个数设定为一个长度为1的数,那么通过这样简单分析可知,我们要么把第一个数字设定为长度为1的数,要么把第最后个数字设定为长度为1的数,那么对应两种情况,我们取最大值即可。

3、我们再来分析如何将-c*d/e这个负数变得尽量小我们将c和d都设定为长度为1的数,那么使得其乘积尽可能的小。然后将其这两个数后边的数都设定成e,(比如123456,我们可以设定3 4是c和d,那么e就是56,这样就能尽量让这个负数尽可能的小)。
对于这个e的长度,我们可以通过枚举来搞定(暴力题暴力做)。
那么我们直接枚举一个位子i,来界限a+b和-c*d/e,位子i之前的数字维护一个a+b最大,位子i后边按照上述过程计算出来,然后将两个数相减,得到一个可行解,然后在枚举位子i的过程中,维护一个最大值即可。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;

char s[25];

int main()
{
    int t,cas = 1;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s",s);
        int n = strlen(s);
        long long ans = -1000000000000000000;
        for(int i=2;i<n-2;i++)
        {
            long long a = 0;
            for(int j=0;j<i-1;j++) a = a * 10 + s[j] - '0';
            long long b = s[i-1] - '0';
            long long tmp = a + b;
            a = s[0] - '0';  b = 0;
            for(int j=1;j<i;j++) b = b * 10 + s[j] - '0';
            if(tmp < a + b) tmp = a + b;
            long long c = s[i] - '0';
            long long d = s[i+1] - '0';
            long long e = 0;
            for(int j=i+2;j<n;j++) e = e * 10 + s[j] - '0';
            ans = max(ans,tmp-c*d/e);
        }
        printf("Case #%d: %I64d\n",cas++,ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值