UVA10410 - Tree Reconstruction(隊列)

來源:互聯網
上載者:User

標籤:http   io   ar   for   sp   cti   代碼   on   c   

題目:UVA10410 - Tree Reconstruction(隊列)


題目大意:給出一棵樹的BFS和DFS遍曆,求這棵數,如果有多種情況輸出一種就可以了。


解題思路:利用BFS將DFS串分段,分成一棵一棵子樹。然後將子樹用佇列儲存體下來,因為先被分出來的子樹,在下一層中也是最先被分段。注意:一定要將根節點分離出去,它不屬於它的子樹。這棵樹不一定是二叉樹。


代碼:

#include <cstdio>#include <queue>#include <vector>using namespace std;const int N = 1005;vector<int> v[N];struct Seg {int l, r;Seg(int l, int r): l(l), r(r) {}};queue<Seg> q;int B[N];int D[N];int n;void solve () {q.push(Seg(0, n));int p = 1;int root;while (!q.empty()) {Seg s = q.front();q.pop();if (s.r - s.l <= 1 || p == n)continue;root = D[s.l];int pre = s.l + 1;//分離根節點for (int i = pre; i < s.r; i++) {if (D[i] == B[p]) {q.push (Seg (pre, i));v[root].push_back (D[i]);p++;pre = i;}}if (pre < s.r) q.push (Seg (pre, s.r));}}int main () {int num;while (scanf ("%d", &n) == 1) {for (int i = 0; i < n; i++) scanf ("%d", &B[i]);for (int i = 0; i < n; i++)scanf ("%d", &D[i]);solve();for (int i = 1; i <= n; i++) {printf ("%d:", i);for (int j = 0; j < v[i].size(); j++)printf (" %d", v[i][j]);printf ("\n");v[i].clear();}}return 0;}


UVA10410 - Tree Reconstruction(隊列)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.