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,要求結(jié)果最大。
【分析】:枚舉負(fù)號的位置,因?yàn)橐拐麄€值最大,C*D應(yīng)該最小,所以C和D都只取一位。
A+B的值最大需要使A或B的位數(shù)盡可能大,即A一位,B為到負(fù)號前的所有位或者B為符號前一位,
A為開頭到負(fù)號前一位位置,兩種情況取最大值。由于C和D都確定了E也隨之確定了。
所以總的來說就是枚舉一下負(fù)號的位置,然后判斷一下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; } View Code
?
轉(zhuǎn)載于:https://www.cnblogs.com/Roni-i/p/7505345.html
總結(jié)
以上是生活随笔為你收集整理的HDU 5938 Four Operations 【字符串处理,枚举,把数字字符串变为数值】的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL数据库 Too many co
- 下一篇: hdu 2553 N皇后问题【dfs】