1. 程式人生 > >RMQ和LCA

RMQ和LCA

RMQ

void ST(int n) {
	for (int i = 1; i <= n; i++)
		dp[i][0] = a[i];
	for (int j = 1; (1 << j) <= n; j++) {//2^j
		for (int i = 1; i + (1 << j) - 1 <= n; i++) {
			dp[i][j] = max(dp[i][j - 1], dp[i + (1 << (j - 1))][j - 1]);
		}
	}
}
int RMQ(int l, int r) {
	if(l>r) return 0;
	int k = 0;
	while ((1 << (k + 1)) <= r - l + 1) k++;
	return max(dp[l][k], dp[r - (1 << k) + 1][k]);
}
void ST()
{
    int i,j,k;
    for(i=1;i<=n;i++)
        MAX[i][0]=f[i];
    k=log((double)(n+1))/log(2.0);
    for(j=1;j<=k;j++)
        for(i=1;i+(1<<j)-1<=n;i++)
            MAX[i][j]=max(MAX[i][j-1],MAX[i+(1<<(j-1))][j-1]);
}
int rmq_max(int l,int r)
{
    if(l>r)
        return 0;
    int k=log((double)(r-l+1))/log(2.0);
    return max(MAX[l][k],MAX[r-(1<<k)+1][k]);
}