我的解法: 建树,递归判断
#include#include #include #include #include using namespace std;struct Node { Node() { wl=wr=dl=dr=0; l=r=0; } int wl; int dl; int wr; int dr; Node* l; Node* r;};Node* build(){ int wl, wr, dl, dr; scanf("%d%d%d%d", &wl, &dl, &wr, &dr); Node* root=new Node; if(wl==0) { Node* left=build(); wl=left->wl + left->wr; root->l=left; } if(wr==0) { Node* right=build(); wr=right->wl + right->wr; root->r=right; } root->wl=wl; root->wr=wr; root->dl=dl; root->dr=dr; return root;}bool equilibrium(Node* root){ if(!root) return true; bool el=equilibrium(root->l); bool er=equilibrium(root->r); if(el&&er) { return (root->wl * root->dl == root->wr * root->dr); } else { return false; }}int main(){#ifndef ONLINE_JUDGE freopen("./uva839.in", "r", stdin);#endif int T; scanf("%d", &T); while(T--) { Node* root=build(); if(equilibrium(root)) printf("YES\n"); else printf("NO\n"); if(T!=0) printf("\n"); } return 0;}
解答解法:
// UVa839 Not so Mobile// Rujia Liu// 题意:输入一个树状天平,根据力矩相等原则判断是否平衡。采用递归方式输入,0表示中间结点// 算法:在“建树”时直接读入并判断,并且无须把树保存下来#includeusing namespace std;// 输入一个子天平,返回子天平是否平衡,参数W修改为子天平的总重量bool solve(int& W) { int W1, D1, W2, D2; bool b1 = true, b2 = true; cin >> W1 >> D1 >> W2 >> D2; if(!W1) b1 = solve(W1); if(!W2) b2 = solve(W2); W = W1 + W2; return b1 && b2 && (W1 * D1 == W2 * D2);}int main() { int T, W; cin >> T; while(T--) { if(solve(W)) cout << "YES\n"; else cout << "NO\n"; if(T) cout << "\n"; } return 0;}