题意是一个大天平有许多小天平组成,要保证每个天平的两端都是平衡的,即力臂*力矩相等。
从图片看起来就是一颗二叉树,用递归方式建树来计算每个子天平的左边重量和右边重量,并判断是否平衡。
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<map> #include<queue> #include<stack> #include<vector> #include<ctype.h> #include<algorithm> #include<string> #define PI acos(-1.0) #define maxn 160 #define INF 1<<25 #define MAX 0x7fffffff typedef long long ll; using namespace std; struct Node { int wl,dl,wr,dr; Node *lchild; Node *rchild; }; Node *root; int jud; int Buildtree(Node *&node,int a,int b,int c,int d) { node=(Node*)malloc(sizeof(Node)); int q,w,e,r; node->dl=b; node->dr=d; if(a>0) node->wl=a; else { scanf("%d%d%d%d",&q,&w,&e,&r); Buildtree(node->lchild,q,w,e,r); node->wl=node->lchild->wl+node->lchild->wr; } if(c>0) node->wr=c; else { scanf("%d%d%d%d",&q,&w,&e,&r); Buildtree(node->rchild,q,w,e,r); node->wr=node->rchild->wl+node->rchild->wr; } } int dfs(Node *&node) { if(jud==1) return 0; if(node->wl*node->dl!=node->wr*node->dr) { jud=1; return 0; } else { if(node->lchild!=NULL) dfs(node->lchild); if(node->rchild!=NULL) dfs(node->rchild); } return 0; } int main() { int tot; scanf("%d",&tot); for(int i=0; i<tot; i++) { jud=0; int a,b,c,d; scanf("%d%d%d%d",&a,&b,&c,&d); Buildtree(root,a,b,c,d); dfs(root); if(jud==0) printf("YES\n"); else printf("NO\n"); if(i<tot-1) printf("\n"); } }
原文:http://blog.csdn.net/ooooooooe/article/details/18825539