在C++中,最大化x + y + z的值,条件是ax + by + cz = n
给定整数a、b、c、n。目标是最大化x、y和z的和,使得ax+by+cz=n。
根据上述公式:
cz=n-(ax+by) z= (n- (ax+by))/c
固定x和y,使用上述公式计算z,对于每个x、y和z。计算和并存储获得的最大和。
输入
n = 6, a = 3, b = 4, c = 5;
输出
maximum x+y+z is 2.
解释 - 对于x=2,y=0,z=0,ax+by+cz=n。
3*2+0*4+0*5=6 = n
输入
n = 4, a = 3, b = 1, c = 2;
输出
maximum x+y+z=4
解释 - 对于x=0,y=4,z=0,ax+by+cz=n。
0*3+4*1+0*2=4 = n
下面程序中使用的算法如下:
整数a、b、c和n用于表达式ax+by+cz=n。
函数maximize(,int n,int a,int b,int c)接收a、b、c和n作为输入,并返回x、y和z的最大可能和,使得ax+by+cz=n。
获取所有可能的ax值,for(i=0;i<=n;i+=a),以及
获取所有可能的by值,for(j=0;j<=n;j+=b),
计算z= (n- (ax+by))/c。
现在x=i/a,y=j/b。计算x+y+z并将结果存储在temp中。
如果temp>=maxx(到目前为止的最大值),则更新maxx。
返回maxx作为所需的和。
示例
#include <bits/stdc++.h>
using namespace std;
int maximize(int n, int a, int b, int c){
int maxx = 0;
// i for possible values of ax
for (int i = 0; i <= n; i += a)
// j for possible values of by
for (int j = 0; j <= n - i; j += b) {
float z = (n - (i + j)) / c;
// If z is an integer
if (floor(z) == ceil(z)) {
int x = i / a;
int y = j / b;
int temp=x+y+z;
if(temp>=maxx)
maxx=temp;
}
}
return maxx;
}
int main(){
int n = 6, a = 3, b = 4, c = 5;
cout <<"Maximized the value of x + y + z :"<<maximize(n, a, b, c);
return 0;
}输出
Maximized the value of x + y + z :2
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP