樹狀陣列關鍵函式和簡單應用

2021-10-09 22:55:21 字數 690 閱讀 6714

簡單來說,是乙個一維陣列,但是可以動態查詢字首和(query()),和在某乙個位置上加上乙個數(add()),並且兩個操作的時間複雜度都是logn。

#include

#include

#include

#include

using

namespace std;

const

int n =

100010

;int tre[n]

;//樹狀陣列下標必須從1開始

int n;

//樹狀陣列中元素的個數

intlowbi

(int x)

void

add(

int x,

int v)

//在第x個位置加上v

intquery

(int x)

//求1-x位置的字首和

intmain()

;for

(int i =

1;i <=

5;i++

)for

(int i =

1; i <=

5; i++

) cout <<

query(5

)-query(2

);//輸出第3個位置到第5個位置的和

}

樹狀陣列應用

一維樹狀陣列常用的3 個函式 int lowbit int x 取x的最低位1,比如4,則返回4,如5,則返回1 void update int i,int val 將第i個元素增加val int sum int i 求前i項的和 return s 以下陣列下標均預設從1開始 應用一假如給你乙個陣列...

樹狀陣列的應用

樹狀陣列的應用1 求逆序數 首先考慮將輸入陣列離散化,因為題目要求輸入的數值可以達到10的9次方,肯定不會開出那麼大的陣列。1.定義乙個結構體 val儲存原值,pos儲存原來在陣列中的位置 2.在對原結構體陣列對val值排序 3.定義儲存離散化資料的陣列flect,flect node i pos ...

樹狀陣列的應用

include include define lowbit i i i const int maxn 100010 int c maxn 樹狀陣列 getsum函式返回前x個整數之和 int getsum int x return sum 返回和 update函式將第x個整數加上v void upd...