1622Trees on the level
哈哈哈哈,我又来啦,这次是一道关于树的题目,不过输入很阴间,我的思路就是先建树,然后判断树中节点是否全都有权
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1622
代码:
#include<iostream> #include<string> #include<algorithm> #include<string.h> #include<cmath> #include<vector> #include<queue> #include<unordered_set> using namespace std; typedef long long ll; #define md (l+r)>>1 #define lson rt<<1,l,mid #define rson rt<<1|1,mid+1,r const int maxn = 257; int tree[maxn][2]; int val[maxn]; int tot; int cnt; vector<string>V[maxn]; bool flg; void build(string& pos, int i, int w, int rt) { if (i == pos.size()) { if (val[rt])flg = 0;//如果该节点已经有权值了(题目说了权值全是postive的才可以这样用,不然就加一个vis数组) val[rt] = w; cnt++;//有权值的节点数目+1 return; } if (pos[i] == 'L') { if (!tree[rt][0])tree[rt][0] = ++tot; build(pos, i + 1, w, tree[rt][0]); } else { if (!tree[rt][1])tree[rt][1] = ++tot; build(pos, i + 1, w, tree[rt][1]); } } void level_order(int rt) {//层序遍历没啥好说的 queue<int>Q; Q.push(rt); bool h = 0; while (!Q.empty()) { int t = Q.front(); Q.pop(); if (h)printf(" "); printf("%d", val[t]); h = 1; if (tree[t][0])Q.push(tree[t][0]); if (tree[t][1])Q.push(tree[t][1]); } printf("\n"); } int num = 0; int main() { //freopen("test.txt", "r", stdin); string m; while (cin >> m) { if (m == "()") { num++; continue; } V[num].push_back(m); } for (int i = 0; i < num; i++) { memset(tree, 0, sizeof(tree));//初始化操作一定要做好,我flg没初始化还去问人家,呜呜呜... memset(val, 0, sizeof(val)); tot = 1;//树中节点个数 cnt = 0;//有权值的节点个数 flg = 1;//预设树是满足条件的 for (auto& j : V[i]) { //对付阴间输入就要用正道的光...STL.. string w = j.substr(1, j.find(',') - 1); int m = atoi(w.c_str()); string path = j.substr(j.find(',') + 1); path.pop_back();//也可以修改上面的substr,但是我难得动脑壳,直接把')'弹出去 build(path, 0, m, 1); if (!flg)break; } if (cnt != tot)flg = 0;//如果个数不相等说明树中有些节点还没有权值,即构不成完整的树 if (flg) { level_order(1); } else { printf("not complete\n"); } } return 0; }