# Uvs: 10700

Source: Internet
Author: User

The expression is composed of numbers and plus signs. The value range is [1, 20 ]. These expressions may lack parentheses. Ask the maximum and minimum values that can be obtained after such expressions are added with parentheses.

Solution: because these numbers are all positive integers, you can use greed. Otherwise, we can see that the maximum value is the addition before multiplication, and the minimum value is the multiplication before addition. Note that the value here must be long because the value of the expression may exceed int.

Code:

`#include <stdio.h>#include <string.h>const int N = 15;char op[N];char str[3 * N];long long num[N];long long caculate_max (int count) {long long temp[N];for (int i = 0; i < count; i++)temp[i] = num[i];for (int i = count - 2; i >= 0; i--)if (op[i] == '+') {temp[i] += temp[i + 1];temp[i + 1] = temp[i];}long long sum = temp[0];for (int i = 0; i < count - 1; i++) {if (op[i] == '*') sum *= temp[i + 1];}return sum;}long long caculate_min (int count) {long long temp[N];for (int i = 0; i < count; i++)temp[i] = num[i];for (int i = count - 2; i >= 0; i--) {if (op[i] == '*')temp[i] = temp[i] * temp[i + 1];}long long sum = temp[0];for (int i = 0; i <= count - 2; i++) {if (op[i] == '+')sum += temp[i + 1];}return sum;}int init () {int t = 0;long long sum;scanf ("%s", str);for (int i = 0; i < strlen (str); i++) {if (str[i] == '+' || str[i] == '*')op[t++] = str[i];else {sum = 0;while (str[i] >= '0' && str[i] <= '9') {sum = sum * 10 + str[i] - '0';i++;}num[t] = sum;i--;}}return t + 1;}int main () {int t;int count;scanf ("%d", &t);while (t--) {count = init();printf ("The maximum and minimum are %lld and %lld.\n", caculate_max(count), caculate_min(count));}return 0;}`

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.