UVa10410 Tree Reconstruction(bfs+dfs确定二叉树)
生活随笔
收集整理的這篇文章主要介紹了
UVa10410 Tree Reconstruction(bfs+dfs确定二叉树)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意就是給你二叉樹的bfs和dfs遍歷,都是結點小的優先遍歷
本來自己沒做出來,不想寫的,做了半天測試數據是對的,但是WA。因為看了一個大佬的解法,讓我感慨萬分,簡潔而直接的解法,正確而清晰的思路,讓我佩服的五體投地。充分運用的bfs,dfs,以及棧的性質,這句話很重要,代碼真是藝術,總存在最簡解法。
#include<iostream> #include <string> #include <string.h> #include<vector> #include<stack> using namespace std; const int maxn = 1000 + 5;int bfs[maxn]; vector<int>tree[maxn];int main() {int n; int temp;while (cin >> n && n) {for (int i = 1; i <= n; i++) {cin >> temp; bfs[temp] = i; tree[i].clear();}int next;cin >> next;stack<int>sp;sp.push(next);for (int i = 1; i < n; i++) {cin >> next;while (1) {int root = sp.top();if (bfs[next] > bfs[root] + 1 || (bfs[root] + 1 == bfs[next] && root > next) || root == next) {//第二個判斷就是結點小的優先搜索tree[root].push_back(next);sp.push(next); //加入要搜索子節點的棧break;}else {sp.pop();//沒有搜索到子節點 回退上一個節點}}}for (int i = 1; i <= n; i++) {cout << i << ":";for (int j = 0,sz= tree[i].size(); j < sz; j++) {cout << " "<<tree[i][j];}cout << endl;}}//system("pause");return 0; }?
總結
以上是生活随笔為你收集整理的UVa10410 Tree Reconstruction(bfs+dfs确定二叉树)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UVa12166 Equilibrium
- 下一篇: UVa810 A Dicey Probl