C++ 砝码问题:根据关系判断天平两侧砝码数量
#include <iostream>
#include <vector>
using namespace std;
int n;
vector<vector<char>> weightRelations;
vector<int> leftWeights;
int countLeftHeavy(int a, int b) {
int count = 0;
for (int i = 0; i < n; i++) {
bool isLeftHeavy = true;
for (int j = 0; j < n; j++) {
if (i == j) continue;
char rel = weightRelations[i][j];
if (rel == '+' && leftWeights[i] <= leftWeights[j]) {
isLeftHeavy = false;
break;
}
if (rel == '-' && leftWeights[i] >= leftWeights[j]) {
isLeftHeavy = false;
break;
}
if (rel == '=' && leftWeights[i] != leftWeights[j]) {
isLeftHeavy = false;
break;
}
}
if (isLeftHeavy) {
if (i == a || i == b) continue; // 排除已选中的砝码
count++;
}
}
return count;
}
int countEqual(int a, int b) {
int count = 0;
for (int i = 0; i < n; i++) {
bool isEqual = true;
for (int j = 0; j < n; j++) {
if (i == j) continue;
char rel = weightRelations[i][j];
if (rel == '+' && leftWeights[i] <= leftWeights[j]) {
isEqual = false;
break;
}
if (rel == '-' && leftWeights[i] >= leftWeights[j]) {
isEqual = false;
break;
}
if (rel == '=' && leftWeights[i] != leftWeights[j]) {
isEqual = false;
break;
}
}
if (isEqual) {
if (i == a || i == b) continue; // 排除已选中的砝码
count++;
}
}
return count;
}
int countRightHeavy(int a, int b) {
int count = 0;
for (int i = 0; i < n; i++) {
bool isRightHeavy = true;
for (int j = 0; j < n; j++) {
if (i == j) continue;
char rel = weightRelations[j][i];
if (rel == '+' && leftWeights[i] >= leftWeights[j]) {
isRightHeavy = false;
break;
}
if (rel == '-' && leftWeights[i] <= leftWeights[j]) {
isRightHeavy = false;
break;
}
if (rel == '=' && leftWeights[i] != leftWeights[j]) {
isRightHeavy = false;
break;
}
}
if (isRightHeavy) {
if (i == a || i == b) continue; // 排除已选中的砝码
count++;
}
}
return count;
}
int main() {
cin >> n;
weightRelations.resize(n, vector<char>(n));
leftWeights.resize(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> weightRelations[i][j];
}
}
int a, b;
cin >> a >> b;
a--;
b--;
for (int i = 0; i < n; i++) {
leftWeights[i] = 1; // 默认所有砝码的质量都是1g
}
int countLeft = countLeftHeavy(a, b);
int countEqual = countEqual(a, b);
int countRight = countRightHeavy(a, b);
cout << countLeft << endl;
cout << countEqual << endl;
cout << countRight << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/if3 著作权归作者所有。请勿转载和采集!