#include #include #include char buf[1024]; long j; typedef struct _tree { struct _tree *left, *right; char op; char var; } tree; void factor(tree **mt); void expression(tree **mt); void term(tree **mt); void error() { printf("seltsam\n"); } int isalpha(char c) { if ((c>='a' && c<='z') || (c>='A' && c<='Z')) return 1; return 0; } void factor(tree **mt) { if (buf[j]=='(') { j++; expression(mt); if (buf[j]==')') j++; else error(); } else { if (isalpha(buf[j])) { *mt = malloc(sizeof(tree)); (*mt)->left = NULL; (*mt)->right = NULL; (*mt)->op = '_'; (*mt)->var = buf[j]; j++; } else error(); } } void term(tree **mt) { *mt = malloc(sizeof(tree)); (*mt)->left = NULL; (*mt)->right = NULL; (*mt)->op = '&'; factor(&(*mt)->left); if (buf[j] == '*' || buf[j] == '/') { (*mt)->op = buf[j]; j++; term(&(*mt)->right); } } void expression(tree **mt) { *mt = malloc(sizeof(tree)); (*mt)->left = NULL; (*mt)->right = NULL; (*mt)->op = '&'; term(&(*mt)->left); if (buf[j]=='+' || buf[j]=='-') { (*mt)->op = buf[j]; j++; expression(&(*mt)->right); } } void treeminus(tree *root) { tree *tp; if (root->op == '-' && root->right && root->right->op != '&') { tp = root->left; root->left = root->right; root->right = root->left->right; root->left->right = root->left->left; root->left->left = tp; } if (root->op != '_' && root->left != NULL) treeminus(root->left); if (root->right) treeminus(root->right); } void treepurge(tree *root) { if (root->op == '&') { tree *p = root->left; root->op = p->op; root->var = p->var; root->left = p->left; root->right = p->right; free(p); } if (root->op != '_' && root->left != NULL) treepurge(root->left); if (root->right) treepurge(root->right); } void printtree(tree *root, char leftop, tree *parent) { if (root->op == '_') printf("%c", root->var); else { int bracket = 0; if (root->right) { bracket = 1; if ((root->op == '*' || root->op == '/') && leftop != '/') bracket = 0; if (root->op == '+' || root->op == '-') { bracket = 0; if (parent && (parent->op == '*' || parent->op == '/')) bracket = 1; if (leftop == '-') bracket = 1; } } if (bracket) printf("("); printtree(root->left, leftop, root); if (root->right) { printf("%c", root->op); printtree(root->right, root->op, root); if (bracket) printf(")"); } } } void freetree(tree *xx) { if (xx->left) freetree(xx->left); if (xx->right) freetree(xx->right); free(xx); } int main() { tree *root; long n, N; fgets(buf, 1024, stdin); N = strtol(buf, NULL, 10); for (n=0; n