封裝線段樹實現基本功能

2022-02-13 11:22:45 字數 2327 閱讀 6863

1. 結點類treenode

/* 樹結點*/

function

treenode

(x, y, val)

2. 線段樹類

通過options可以傳入pushup函式設定父子結點關係,root記錄線段樹根節點

function

segtree

(options)

3. 建樹
segtree.prototype.

build

=function

(x, y)

/* 建立結點 */

let node =

newtreenode

(x, y)

;/* 建立子結點 */

let mid = math.

floor

(x + y >>1)

; node.left =

this

.build

(x, mid)

; node.right =

this

.build

(mid +

1, y)

;/* 關聯父子結點 */

this

.pushup

(node, node.left, node.right)

;return node;

}

4. 查詢
segtree.prototype.

query

=function

(tgtx, tgty, node)

/* 將查詢到的值進行疊加 */

let count =0;

let m = math.

floor

(x + y >>1)

;if(tgty <= m)

count +=

this

.query

(tgtx, tgty, node.left);if

(tgtx > m)

count +=

this

.query

(tgtx, tgty, node.right)

;return count;

}

5. 更新
segtree.prototype.

update

=function

(tgtx, tgty, val, node)

let mid = math.

floor

(tgtx + tgty >>1)

;if(tgtx <= mid)

this

.update

(tgtx, tgty, val, node.left)

if(tgty > mid)

this

.update

(tgtx, tgty, val, node.right)

;/* 更新父節點 */

this

.pushup

(node, node.left, node.right)

;}

6. 刪除
segtree.prototype.

delete

=function

(tgtx, tgty, node)

let mid = math.

floor

(tgtx + tgty >>1)

;let flagx, flagy;

//標識左右結點是否刪除

if(tgtx <= mid)

if(tgty > mid)

/* 更新父節點 */

this

.pushup

(node, node.left, node.right);if

(flagx) node.left =

null;if

(flagy) node.right =

null

;}

測試**
/* 測試 */

let tree =

newsegtree(}

)console.

log(tree.

query(0

,8))

//1tree.

update(0

,8,1

)console.

log(tree.

query(0

,8))

//10

ASP基本功能實現

修改資料庫的記錄 若要修改資料庫的記錄,首先使用ado鏈結到access資料庫ntopsamp.mdb,下sql指令尋找待修改的記錄,將結果傳回到rs1的recordset當中,asp程式碼如下 set rs server.createobject adodb.recordset sql selec...

Servlet基本功能實現

生命週期 3.0版本以上的支援,版本號就是建立web專案的版本 webservlet註解 可以定義多個路徑,陣列形式 學習servlet之前應該了解下請求頭的知識 request可以用來獲取請求行的各種引數,知道方法即可,這些方法要寫在servlet的doget方法中 域物件,乙個有作用範圍的物件 ...

Bash基本功能

history 選項 歷史命令儲存檔案 c 清空歷史命令 w 把快取中的歷史命令寫入命令儲存檔案 歷史命令預設儲存1000條,可以在環境變數配置檔案 etc profile中進行修改 必須重新登陸,歷史命令可以儲存檔案 歷史命令的呼叫 使用上,下箭頭呼叫以前的歷史命令 使用 n 重複執行第n條命令 ...