Overview: (1)Data Structure: Interval Tree and Poj3264

来源:互联网 发布:java excel 下拉联动 编辑:程序博客网 时间:2024/05/21 02:48

Interval Tree能够将查询问题时间复杂度降低到O(logn)量级,使用线段树解决问题时关键需要弄清区间节点里存储哪种信息比较有利于解决问题。这里以POJ 3264为例,子函数使用递归实现,注意子函数中的终止条件。

#include <cstdio>#include <algorithm>#define MyMax -999999#define MyMin 999999using namespace std;struct cNode{    int L,R;    int cMin,cMax;    cNode * Left, * Right;};cNode Tree[400001];int nCount; // the nodes number in the interval treeint qMin,qMax;void BiuldTree(cNode * pRoot, int L, int R){    pRoot->L = L;    pRoot->R = R;    pRoot->cMin = MyMin;    pRoot->cMax = MyMax;    if(L == R)        return;    nCount++;    pRoot->Left = Tree + nCount;    nCount++;    pRoot->Right = Tree + nCount; //Biuld the tree with the level order    BiuldTree(pRoot->Left,L,(L + R) / 2);    BiuldTree(pRoot->Right,(L + R) / 2 + 1, R);}void InsertTree(cNode * pRoot, int i ,int number){    pRoot->cMax = max(pRoot->cMax, number);    pRoot->cMin = min(pRoot->cMin, number);    if(pRoot->L == pRoot->R)        return;    if(i <= (pRoot->L + pRoot->R) / 2) // Continue to insert in the left subtree        InsertTree(pRoot->Left,i,number);    else        InsertTree(pRoot->Right,i,number);}void QueryTree(cNode * pRoot, int s, int e){    if( pRoot->L >= s && pRoot->R <= e)    {        qMin = min(qMin,pRoot->cMin);        qMax = max(qMax,pRoot->cMax);        return;    }    if( e < pRoot->L || s >pRoot->R)        return;    QueryTree( pRoot->Left, s, e );    QueryTree( pRoot->Right, s, e );}int main(){    int m,n,s,e;    int num;    scanf("%d %d",&n,&m);// Input n numbers and m query    BiuldTree(Tree,1,n);// biuld a interval tree with size of n    for(int i = 1; i <= n; i++)    {        scanf("%d",&num);        InsertTree(Tree,i,num);// Insert the i-th number into the interval tree    }    for(int i = 1; i<= m; i++)    {        scanf("%d %d",&s,&e);        qMin = MyMin;        qMax = MyMax;        QueryTree(Tree,s,e); // Deal with the request of query        printf("%d\n",qMax-qMin); //Calculate the differences of the max and the min in the required interval    }    return 0;}
0 0
原创粉丝点击