标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 4117 Accepted Submission(s): 1802
题解:省赛有道树的形状相同的题,我还以为这个也是形状,错了几次,这个数值和树形都相同;想到省赛那题一直wa,现在想想要想判断树形相同,先序中序遍历都应该相同;我只是判断了位置,应该是不正确的。。。
这个不知道为啥只要先序就可以了。。。
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> using namespace std; typedef struct Node{ Node *l, *r; char c; Node(){l = NULL; r = NULL;} }*tree, Node; void build(Node* &p, char c){ if(p == NULL){ p = new Node(); p->c = c; return; } if(c < p->c) build(p->l, c); else build(p->r, c); } void InOrder(tree p, string& s){ if(p == NULL)return; InOrder(p->l, s); s += p->c; InOrder(p->r, s); } void PreOrder(tree p, string& s){ if(p == NULL)return; s += p->c; PreOrder(p->l, s); PreOrder(p->r, s); } int main(){ int n; char dt[15]; string ans1, ans2, s1, s2; while(scanf("%d", &n), n){ Node *p; cin >> dt; p = NULL; for(int i = 0; dt[i]; i++){ build(p, dt[i]); } ans1 = ""; PreOrder(p, ans1); ans2 = ""; InOrder(p, ans2); // cout << ans1 << endl << ans2 << endl; for(int j = 0; j < n; j++){ p = NULL; cin >> dt; for(int i = 0; dt[i]; i++){ build(p, dt[i]); } s1 = ""; PreOrder(p, s1); s2 = ""; InOrder(p, s2); // cout << s1 << endl << s2 << endl; if(s1 == ans1 && s2 == ans2) puts("YES"); else puts("NO"); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/5574787.html