暑假集訓7月30日 二叉樹 堆 樹堆

2021-10-08 17:17:41 字數 3524 閱讀 9450

a:

思路:二叉樹插入+前序遍歷

#include

using

namespace std;

const

int maxn =

100100

;int a[maxn]

;int k;

struct node

;node*

insert

(node* p,

int x)

else

}void

preorder

(node* p)

intmain()

preorder

(p);

for(

int i =

1; i <= k; i++

)printf

("\n");

}}

b:

思路:二叉樹插入+查詢 模擬精靈移動

#include

#include

#include

using

namespace std;

struct node

;node*

insert

(node* p,

int x)

else

}void

find

(node* p,

int x)

else

if(x >= p-

>val)

}int

main()

int q;

cin >> q;

while

(q--)}

}

c:

思路:優先佇列

#include

#include

#include

using

namespace std;

struct node

tmp;

bool

operator

<

(const node& n1,

const node& n2)

priority_queue pq;

string s;

intmain()

}else

}}

e:

思路:後面不再出現的最小的編號就是葉子節點,使用優先佇列逐個彈出構建樹,然後再進行前序遍歷

#include

#include

#include

#include

#include

#include

using

namespace std;

int f[55]

, ans[55]

;vector <

int> vec[55]

;string s;

priority_queue<

int, vector<

int>

, greater<

int>

> pq;

void

dfs(

int x)

printf

(")");

vec[x]

.clear()

;}intmain()

if(n !=-1

)dfs

(f[n]);

else

printf

("(1)");

//輸入為0

printf

("\n");

}}

f:

思路:直接利用stl中set是紅黑樹實現的特性,從set的頭部和尾部進行操作,單次操作複雜度o(logn)

#include

#include

using

namespace std;

struct node};

set st;

intmain()

else

if(op ==2)

set::iterator it =

--st.

end();

printf

("%d\n"

, it-

>id)

; st.

erase

(it);}

else

if(op ==3)

set::iterator it = st.

begin()

;printf

("%d\n"

, it-

>id)

; st.

erase

(it);}

}}

g:

思路:stl中crope 可代替可持續化

#include

#include

using

namespace __gnu_cxx;

crope r, his[

50050

], tmp;

char s[

250]

;int

main()

else

if(op ==2)

else

if(op ==3)

}}

h:

思路:樹狀陣列lowbit,對當前的編號減去lowbit再+1得到最深的左孩子,最深的右孩子同理

#include

#include

#include

using

namespace std;

#define ll long long

intmain()

}

i:

思路:構建以字母為值的二叉樹,實現插入功能,再進行前序遍歷

#include

#include

#include

using

namespace std;

#define ll long long

struct node

;node*

insert

(node* p,

char c)

else

}void

preorder

(node *p)

string s;

string str;

intmain()

preorder

(p);

printf

("\n");

return0;

}if(s !=

"*")

else

preorder

(p);

printf

("\n");

str.

clear()

;}}}

樹 二叉樹 堆

樹 樹是乙個無向無環圖,n個節點正好有n 1條邊,再任意加上一條邊就可以構成迴路。乙個結點的上乙個結點是這個結點父結點,這個節點是子結點,並且父結點和子結點是相對的。特別的,如果乙個結點沒有父結點,那這個結點是根節點 乙個結點沒有子結點,它是葉節點。二叉樹 如果乙個樹除了葉結點之外的其他每個結點都不...

樹3 1 二叉樹 堆

一 堆的性質 結構性 用陣列表示的完全二叉樹 有序性 任意一結點的關鍵字是其子樹所有結點的最大值 或最小值 二 最大堆的操作 1 建立乙個空的最大堆,堆從下標為1的地方開始存放 根結點下標為1 2 最大堆的插入 首先,把要插入的結點放在陣列的末尾,假設下標為h size 1 再將它與父結點比較,如果...

二叉樹應用 堆

本例中實現了最小堆的構造 插入 刪除。最小堆表示乙個非終端節點均不大於其左右孩子節點。最小堆用完全二叉樹表示,但是二叉樹存入一維陣列中。將完全二叉樹存入陣列,有一些性質。先將二叉樹從上到下,從左到右給每個節點編號0,1.n。那個乙個節點編號i,他的左孩子編號為2 i 1,右孩子編號2 i 2。完全二...