RMQ转换成LCA <O(N), O(1)>

参考资料:http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=lowestCommonAncestor#A O(N), O(1) algorithm for the restricted RMQ


#include "stdio.h"
#include "stdlib.h"

#define M 100

int num[M] = {3, 9, 1, 33, 20, 18, 52, 0, 10, 7};
int n = 10;

typedef struct _Node{
	int pos;
	struct _Node* pare;
	struct _Node* lf;
	struct _Node* rt;
}Node, *pNode;

pNode st[M];
int top;

void RMQ_2_LCA(pNode* r){
	pNode w;
	int k, i;
	top = -1;
	for(i=0; i<n; i++){
		w = (pNode)malloc(sizeof(Node));
		w->pos = i;
		w->lf = w->rt = 0;

		k = top;
		while(k>=0 && num[i]<num[st[k]->pos])
			k--;
		if(k>=0){
			st[k]->rt = w;
			w->pare = st[k];
		}
		if(k<top)
			w->lf = st[k+1];
		st[++k] = w;
		top = k;
	}
	st[0]->pare = 0;
	*r = st[0];
}

void show(pNode r){
	if(!r) return;
	printf("%d ", num[r->pos]);
	show(r->lf);
	show(r->rt);
}

void main(){
	pNode root;
	RMQ_2_LCA(&root);
	show(root); printf("\n");
}

show函数打出来的不好看,自己调试,看看树的结构

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值