Four Operations

_Yuh_發表於2020-11-05

交了八次才過,太煎熬了…在這個題上肝了一個多小時…
還是太菜了,因為一些細節而浪費了很多時間.
題目連結

題目

Little Ruins is a studious boy, recently he learned the four operations!

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).

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

Now please help him to get the largest result.

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.

因個人能力有限只會暴力做這道題,思路就是計算減號前的所有情況中的最大值,和減號之後所有情況中的最小值,取其差的最大值.比較麻煩點的就是算出所有減號前兩數相加的情況和減號後a*b/c的情況.

一開始因為將ans設為-1(沒有足夠小),一直wa,也沒發現這有錯,後來拿自己qq號做樣例輸入一下試了試,發現輸出的最大值應該是-7,但結果是-1,於是就發現了這個小bug,於是就ac了hhh.

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define ll long long
using namespace std;
const int maxn = 1e5+10;
const ll inf = 9223372036854775800;

ll cal(char str[],int l,int r)
{
    ll a=0,base=1;
    for(int i=r; i>=l; i--)
    {
        a+=(str[i]-'0')*base;
        base*=10;
    }
    return a;
}

int main()
{
    char str[25];
    int t;
    scanf("%d",&t);
    for(int C=1; C<=t; C++)
    {
        scanf("%s",str);
        int n = strlen(str);
        ll ans = -inf;
        ll a,b,c,d,e;
        for(int i=n-4; i>=1; i--)
        {
            ll L=-1,R=inf;
            for(int j=0; j<i; j++)
            {
                a = cal(str,0,j);
                b = cal(str,j+1,i);
                L=max(L,a+b);
            }
            for(int j=n-3; j>=i+1; j--)
            {
                for(int k=j+1; k<=n-2; k++)
                {
                    c = cal(str,i+1,j);
                    d = cal(str,j+1,k);
                    e = cal(str,k+1,n-1);
                    R=min(R,c*d/e);
                }
            }
            ans=max(ans,L-R);
        }
        printf("Case #%d: %lld\n",C,ans);
    }
    return 0;
}

相關文章