HDU 5938 Four Operations 字符串处理,枚举,把数字字符串变为数值
Posted Roni
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 5938 Four Operations 字符串处理,枚举,把数字字符串变为数值相关的知识,希望对你有一定的参考价值。
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
【题意】:给一个字符串,按+, -, *, /的顺序插入将字符串分成a+b-c*d/e,要求结果最大。
【分析】:枚举负号的位置,因为要使整个值最大,C*D应该最小,所以C和D都只取一位。
A+B的值最大需要使A或B的位数尽可能大,即A一位,B为到负号前的所有位或者B为符号前一位,
A为开头到负号前一位位置,两种情况取最大值。由于C和D都确定了E也随之确定了。
所以总的来说就是枚举一下负号的位置,然后判断一下A+B的最大值就可以了。
【代码】:
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> #include <string> const int maxn=25; const int inf=0x3f3f3f3f; typedef long long ll; using namespace std; char a[maxn]; int num[maxn]; ll f(int s,int e) { ll res=0; for(int i=s; i<=e; i++) { res = res*10 + num[i] ; } return res; }// int main() { int t; scanf("%d",&t); for(int cas=1;cas<=t;cas++) { scanf("%s",a); int len=strlen(a); ll ans = -inf; for(int i=0;i<len;i++) { num[i+1]=a[i]-‘0‘; } for(int i=2;i<=len-3;i++) { ll add,c,d,e; add=max((f(1,i-1)+f(i,i)) , (f(1,1)+f(2,i))); c=num[i+1]; d=num[i+2]; e=f(i+3,len); ans=max(ans,add-c*d/e); } printf("Case #%d: %lld\n",cas,ans); } return 0; }
以上是关于HDU 5938 Four Operations 字符串处理,枚举,把数字字符串变为数值的主要内容,如果未能解决你的问题,请参考以下文章
HDU 5938 Four Operations 贪心(中国大学生程序设计竞赛(杭州))
HDU 5938 Four Operations 字符串处理,枚举,把数字字符串变为数值
[HDOJ5938]Four Operations(暴力,DFS)
Four-operations: 使用node.js实现四则运算程序