C++ 程序,找出任意代数表达式的最大值


这是一个 C++ 程序,用以找出任意代数表达式的最大值。形式为 (x1 + x2 + x3 + . . . + xa) * (y1 + y2 + . . . + yb) 的代数表达式和 (a + b) 整数已给出。考虑所有可能的 a 个数字和剩余 b 个数字组合,并计算它们的值,从中可以得出最大值。

算法

Begin
   function MaxValue() :
   Arguments:
   a[]=array which store the elements.
   x, y=integers.
   Body of the function:
   1) Find the sum of array elements.
   2) Initialize s = 0.
   3) Make for loop i = 0 to (x + y-1) Shift the integers by 25 so that they become positive .
   4) Declare a boolean array p[i][j] that represents true if sum j can be reachable by choosing i numbers.
   5) Initialization of the array.
   6) Make for loop i = 0 to (x + y)-1 to determine If p[i][j] is true, that means it is possible to select i numbers from (x + y) numbers to sum upto j.
   7) Initialize max_value = -INF.
   8) Make for loop i = 0 to (MAX * MAX + 1)-1 to Check if a particular sum can be reachable by choosing n numbers.
   if (p[x][i])
      Get the actual sum as we shifted the numbers by 25 to avoid negative indexing in array .
   9) Print the max_value.
End

实例

#include <bits/stdc++.h>
using namespace std;
#define INF 1e9
#define MAX 25
int MaxValue(int a[], int x, int y) {
   int s= 0;
   for (int i = 0; i < (x + y); i++) {
      s+= a[i];
      a[i] += 25;
   }
   bool p[MAX+1][MAX * MAX + 1];
   //Initialize the array to 01.
   memset(p, 0, sizeof(p));
   p[0][0] = 1;
   for (int i = 0; i < (x + y); i++) {
      //k can be at max x because the
      // left expression has x numbers
      for (int k = min(x, i + 1); k >= 1; k--) {
         for (int j = 0; j < MAX * MAX + 1; j++) {
            if (p[k - 1][j])
            p[k][j + a[i]] = 1;
         }
      }
   }
   int max_value = -INF;
   for (int i = 0; i < MAX * MAX + 1; i++) {
      if (p[x][i]) {
         int tmp = i - 25 * x;
         max_value = max(max_value, tmp * (s - tmp));
      }
   }
   cout << "Maximum Value: " << max_value ;
}
int main() {
   int x = 2, y = 2; //input is taken of
   x and y.
   int ar[] = { 7,6,4,3 };
   MaxValue(ar, x, y);
   return 0;
}

输出

Maximum Value: 100

更新日期: 2019-07-30

232 次浏览

开启你的职业生涯

完成课程,获得认证

开始
广告