HDU 5938 Four Operations(思维)

来源:互联网 发布:独立ip linux虚拟主机 编辑:程序博客网 时间:2024/05/16 16:00

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;}
原创粉丝点击