C++ 算法:解决不等式矛盾问题,找到最少矛盾数量的解
以下是一个 C++ 程序,用于找到最少矛盾数量的解:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
vector<pair<char, int>> inequalities(n);
for (int i = 0; i < n; i++) {
cin >> inequalities[i].first >> inequalities[i].second;
}
sort(inequalities.begin(), inequalities.end(), [](const pair<char, int>& a, const pair<char, int>& b) {
if (a.second == b.second) {
return a.first < b.first;
}
return a.second < b.second;
});
int conflicts = 0;
int maxInequalities = 0;
int count = 0;
char lastOp = ' ';
int lastValue = 0;
for (int i = 0; i < n; i++) {
char op = inequalities[i].first;
int value = inequalities[i].second;
if (op == 'L') {
if (lastOp == 'G' && value < lastValue) {
conflicts++;
}
} else {
if (lastOp == 'L' && value > lastValue) {
conflicts++;
}
}
if (conflicts == 0) {
count++;
maxInequalities = max(maxInequalities, count);
} else {
count = 0;
}
lastOp = op;
lastValue = value;
}
cout << n - maxInequalities << endl;
return 0;
}
该程序首先读取输入的不等式数量 n,然后读取 n 个不等式。然后,它对不等式进行排序,按照不等式的值和操作符进行排序。然后,它遍历排序后的不等式,通过比较不等式和前一个不等式的操作符和值,来判断是否有矛盾。如果没有矛盾,则增加当前满足条件的不等式数量 count,并更新最大数量 maxInequalities。如果有矛盾,则重置 count 为 0。最后,输出 n 减去最大数量 maxInequalities,即最少的矛盾数量。
其中 L v 表示 x <= v,G v 表示 x >= v
希望对你有所帮助!
原文地址: https://www.cveoy.top/t/topic/b781 著作权归作者所有。请勿转载和采集!