Files
Data-Structure/Algorithm/Recursion/UVa839 天平Not_so_Mobile.cpp
2025-08-30 21:59:50 +08:00

59 lines
1.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <iostream>
//前序遍历 递归的天花板
using namespace std;
struct mobile{
double lw, ll, rw, rl;
double weight;
mobile* left;
mobile* right;
mobile(double a, double b, double c, double d) : lw(a), ll(b), rw(c), rl(d), left(nullptr), right(nullptr) {}
};
bool solve(mobile* &x){
double a, b, c, d;
bool b1 = true, b2 = true;
cin >> a >> b >> c >> d;
x = new mobile(a, b, c, d);
if(!x->lw) b1 = solve(x->left);
if(!x->rw) b2 = solve(x->right);
double leftWeight = x->left ? x->left->weight : x->lw;
double rightWeight = x->right ? x->right->weight : x->rw;
x->weight = leftWeight + rightWeight;
//关注return如果再solve一遍那就是多次递归了不能再solve了
return b1 && b2 && (leftWeight * x->ll == rightWeight * x->rl);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
string tmp;
getline(cin, tmp); // 读取第一行后的换行
for (int i = 0; i < n; i++) {
mobile* root = nullptr;
bool ok = solve(root);
cout << (ok ? "YES" : "NO") << "\n";
if (i != n - 1) cout << "\n"; // 两个查询之间空一行
}
/*
for(int i = 0; i < n - 1; i++){
cin >> a >> b >> c >> d;
mobile* tmp = new mobile(a, b, c, d);
if(a && !b){
}
}
这是不好的,应该是自然而然地形成一棵树
*/
return 0;
}