UVA 839 Not so Mobile
DFS;
判断平衡;
平衡是指各个子节点都需要平衡,然后若成立则YES 不成立则NO;
递归的输入然后直接判断即可。
若左子树的重量未确定,则向左递归;
若右子树未确定,则向右递归;
直到底层判断节点是否平衡,然后向上返回整个的重量,层层回溯,然后判断 相应层是否平衡。
#include<algorithm> #include<iostream> #include<cstring> #include<cstdio> #include<vector> #include<queue> #include<set> using namespace std; bool flag; int dfs() { int a, l1, b, l2; scanf("%d%d%d%d",&a,&l1,&b,&l2); if(a==0) a=dfs(); if(b==0) b=dfs(); if(a*l1!=b*l2) flag=false; return a+b; } int main() { int t; bool s; scanf("%d",&t); s=false; while(t--) { if(s) puts(""); s=true; flag=true; dfs(); if(flag) printf("YES\n"); else printf("NO\n"); } return 0; }