699 - The Falling Leaves
来源:互联网 发布:淘宝网免单 编辑:程序博客网 时间:2024/05/22 05:07
感觉这个题目就是在考察非递归先序建树,首先将所有的数据全部读入进来,然后利用栈非递归建树。将根节点所在的标志记为0,如果同时如果从当前节点向左,则相应的标志减一,如果是向右,则相应的标志加一,同时建立相应的标志到该标志的“总数”的映射,最后输出即可。对每个节点,设置一个pos,来记录相应的标志,具体的实现见源代码:
#include<iostream>#include<vector>#include<string>#include<set>#include<stack>#include<queue>#include<map>#include<algorithm>#include<cmath>#include<iomanip>#include<sstream>using namespace std;typedef struct node{int val;struct node* left, *right;int pos;node(int value){val = value; left = NULL;right = NULL;}}node;int main(){string s;map<int, int> in2in;int Case = 0;stack<node*> st;int pos;vector<int> data;while (getline(cin, s)){if (s == "-1") break;stringstream ss(s);int t;while (ss >> t){data.push_back(t);}}int position = 0;while (position < data.size()){pos = 0;node* root = new node(data[position]);root->pos = 0;st.push(root);in2in[pos] = data[position];position++;int length = data.size();while (position < length && !st.empty()){node *temp = st.top();pos = temp->pos;while (data[position] != -1){temp->left = new node(data[position]);temp = temp->left;pos--;temp->pos = pos;if (in2in.find(pos) == in2in.end()) in2in[pos] = data[position];else in2in[pos] += data[position];position++;st.push(temp);}position++;while (position < length&&data[position] == -1){st.pop();if (st.empty()) break;temp = st.top();position++;pos = temp->pos;}if (position < length&&data[position] != -1){st.pop();temp->right = new node(data[position]);temp = temp->right;pos++;temp->pos = pos;if (in2in.find(pos) == in2in.end()) in2in[pos] = data[position];else in2in[pos] += data[position];st.push(temp);position++;}}Case++;cout << "Case " << Case << ":" << endl;for (auto it = in2in.begin(); it != in2in.end();){cout << it->second;it++;if (it != in2in.end()) cout << " ";}cout << endl << endl;in2in.clear();position++;}//system("pause");return 0;}
阅读全文
0 0
- 699 - The Falling Leaves
- 699 - The Falling Leaves
- 699 - The Falling Leaves
- 699 - The Falling Leaves
- 699 - The Falling Leaves
- 699 - The Falling Leaves
- 699 - The Falling Leaves
- 699 - The Falling Leaves
- 699 - The Falling Leaves
- 699 - The Falling Leaves
- uva 699 - The Falling Leaves
- uva 699 The Falling Leaves
- uva 699 - The Falling Leaves
- UVa 699 - The Falling Leaves
- 699 - The Falling Leaves---递归
- UVA 699 - The Falling Leaves
- 699_uva The Falling Leaves
- UVa 699 - The Falling Leaves
- 数据结构
- 关于python的计算方式
- Nexus3搭建Maven私有库(一)
- 13读书笔记之研究碎片
- 怎样让你的网页更快的被搜索到
- 699 - The Falling Leaves
- map and pair (1)
- Android高效加载大图、多图解决方案,有效避免程序OOM
- a标签没有disabled属性
- bzoj1031后缀数组——绝对的详解绝对的易懂
- 求树的总结点数量,叶子节点数
- 常用Linux指令之chown指令
- 作业:球钟问题 球可以代表1分钟,5分钟,1小时。 比如1分钟的球有4个,5分钟的球有8个,1小时的球有10个,对应的时间就是10:44 规定:1分钟的球最多有4个,5分钟的球最多有11个,1小时的
- 51Nod-1673-树有几多愁