### 华为OD 2024 E卷:判断不等式组是否满足约束条件
#### 算法设计思路
该问题的核心在于解析不等式、验证每条不等式的成立情况,并计算左侧表达式与右侧目标值的最大差值。以下是具体的实现方法:
1. **输入数据结构化**
输入包括四个主要部分:
- `coefficients`:二维数组,表示每个变量的系数矩阵。
- `variables`:一维数组,表示每个变量的具体取值。
- `targets`:一维数组,表示每个不等式右边的目标值。
- `constraints`:字符串数组,定义了不等式的关系(如 `<`, `<=`, `>`, `>=`, `=`)。
2. **逐项验证不等式**
对于每一个不等式,先根据系数矩阵和变量值计算左侧表达式的实际数值,再依据对应的约束关系进行比较。如果某一条不等式未被满足,则整个不等式组无法通过检验[^1]。
3. **最大差值计算**
如果所有不等式均成立,则进一步计算左侧表达式与目标值之间的绝对差值,并记录其中的最大值作为结果输出[^5]。
---
#### JavaScript 实现代码
以下提供基于 JavaScript 的解决方案:
```javascript
function checkInequalities(coefficients, variables, targets, constraints) {
let maxDifference = Number.MIN_SAFE_INTEGER;
let allSatisfied = true;
for (let i = 0; i < coefficients.length; i++) {
const coeffsRow = coefficients[i];
const targetValue = targets[i];
const constraint = constraints[i];
// 计算左侧表达式的值
const leftSide = coeffsRow.reduce((sum, coeff, index) => sum + coeff * variables[index], 0);
// 判断当前不等式是否成立
switch (constraint) {
case '>':
if (!(leftSide > targetValue)) { allSatisfied = false; }
break;
case '>=':
if (!(leftSide >= targetValue)) { allSatisfied = false; }
break;
case '<':
if (!(leftSide < targetValue)) { allSatisfied = false; }
break;
case '<=':
if (!(leftSide <= targetValue)) { allSatisfied = false; }
break;
case '=':
if (!(Math.abs(leftSide - targetValue) < 1e-9)) { allSatisfied = false; } // 浮点误差考虑
break;
default:
throw new Error('Invalid constraint');
}
// 更新最大差值
if (allSatisfied && Math.abs(leftSide - targetValue) > maxDifference) {
maxDifference = Math.floor(Math.abs(leftSide - targetValue));
}
}
return allSatisfied ? maxDifference : 'Constraints not satisfied';
}
// 示例调用
const coefficients = [[1, 2, 3], [4, 5, 6]];
const variables = [1, 2, 3];
const targets = [10, 32];
const constraints = ['<', '='];
console.log(checkInequalities(coefficients, variables, targets, constraints)); // 输出结果
```
---
#### Java 实现代码
以下是基于 Java 的解决方案:
```java
import java.util.*;
public class InequalityChecker {
public static int checkInequalities(double[][] coefficients, int[] variables, double[] targets, String[] constraints) {
boolean allSatisfied = true;
int maxDifference = Integer.MIN_VALUE;
for (int i = 0; i < coefficients.length; i++) {
double[] rowCoeffs = coefficients[i];
double targetValue = targets[i];
String constraint = constraints[i];
// 计算左侧表达式的值
double leftSide = 0;
for (int j = 0; j < rowCoeffs.length; j++) {
leftSide += rowCoeffs[j] * variables[j];
}
// 判断当前不等式是否成立
switch (constraint) {
case ">":
if (!(leftSide > targetValue)) { allSatisfied = false; }
break;
case ">=":
if (!(leftSide >= targetValue)) { allSatisfied = false; }
break;
case "<":
if (!(leftSide < targetValue)) { allSatisfied = false; }
break;
case "<=":
if (!(leftSide <= targetValue)) { allSatisfied = false; }
break;
case "=":
if (!isCloseEnough(leftSide, targetValue)) { allSatisfied = false; }
break;
default:
System.out.println("Invalid constraint");
return -1;
}
// 更新最大差值
if (allSatisfied && Math.abs(leftSide - targetValue) > maxDifference) {
maxDifference = (int)Math.floor(Math.abs(leftSide - targetValue));
}
}
return allSatisfied ? maxDifference : -1; // 返回 -1 表示约束未满足
}
private static boolean isCloseEnough(double a, double b) {
return Math.abs(a - b) < 1e-9;
}
public static void main(String[] args) {
double[][] coefficients = {{1, 2, 3}, {4, 5, 6}};
int[] variables = {1, 2, 3};
double[] targets = {10, 32};
String[] constraints = {"<", "="};
System.out.println(checkInequalities(coefficients, variables, targets, constraints));
}
}
```
---
#### Python 实现代码
以下是基于 Python 的解决方案:
```python
def check_inequalities(coefficients, variables, targets, constraints):
max_difference = float('-inf')
all_satisfied = True
for i in range(len(coefficients)):
coeffs_row = coefficients[i]
target_value = targets[i]
constraint = constraints[i]
# 计算左侧表达式的值
left_side = sum(c * v for c, v in zip(coeffs_row, variables))
# 判断当前不等式是否成立
if constraint == '>':
if not (left_side > target_value): all_satisfied = False
elif constraint == '>=':
if not (left_side >= target_value): all_satisfied = False
elif constraint == '<':
if not (left_side < target_value): all_satisfied = False
elif constraint == '<=':
if not (left_side <= target_value): all_satisfied = False
elif constraint == '=':
if abs(left_side - target_value) > 1e-9: all_satisfied = False
else:
raise ValueError("Invalid constraint")
# 更新最大差值
if all_satisfied and abs(left_side - target_value) > max_difference:
max_difference = int(abs(left_side - target_value))
return max_difference if all_satisfied else "Constraints not satisfied"
# 示例调用
coefficients = [[1, 2, 3], [4, 5, 6]]
variables = [1, 2, 3]
targets = [10, 32]
constraints = ['<', '=']
print(check_inequalities(coefficients, variables, targets, constraints))
```
---
#### C++ 实现代码
以下是基于 C++ 的解决方案:
```cpp
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
bool is_close_enough(double a, double b) {
return fabs(a - b) < 1e-9;
}
int check_inequalities(const vector<vector<double>>& coefficients,
const vector<int>& variables,
const vector<double>& targets,
const vector<string>& constraints) {
bool all_satisfied = true;
int max_difference = INT_MIN;
for (size_t i = 0; i < coefficients.size(); ++i) {
const auto& coeffs_row = coefficients[i];
double target_value = targets[i];
string constraint = constraints[i];
// 计算左侧表达式的值
double left_side = 0;
for (size_t j = 0; j < coeffs_row.size(); ++j) {
left_side += coeffs_row[j] * variables[j];
}
// 判断当前不等式是否成立
if (constraint == ">" && !(left_side > target_value)) all_satisfied = false;
else if (constraint == ">=" && !(left_side >= target_value)) all_satisfied = false;
else if (constraint == "<" && !(left_side < target_value)) all_satisfied = false;
else if (constraint == "<=" && !(left_side <= target_value)) all_satisfied = false;
else if (constraint == "=" && !is_close_enough(left_side, target_value)) all_satisfied = false;
else {}
// 更新最大差值
if (all_satisfied && abs(left_side - target_value) > max_difference) {
max_difference = floor(abs(left_side - target_value));
}
}
return all_satisfied ? max_difference : -1; // 返回 -1 表示约束未满足
}
int main() {
vector<vector<double>> coefficients = {{1, 2, 3}, {4, 5, 6}};
vector<int> variables = {1, 2, 3};
vector<double> targets = {10, 32};
vector<string> constraints = {"<", "="};
cout << check_inequalities(coefficients, variables, targets, constraints) << endl;
return 0;
}
```
---
###