$n\log_3n$预处理的 Sparse Table ST表

来源:互联网 发布:java判断字符串为空格 编辑:程序博客网 时间:2024/06/16 16:57

nlogn预处理的Sparse Table大家都会写吧?
稍微把它改一点,就可以变成nlog3n预处理的。
当然常数可能大一点,这个我没有详细计算。

int pow3(int x) {    if(x == 0) return 1;    if(x == 1) return 3;    int tmp = pow3(x/2);    return tmp*tmp*(x%2==1?3:1);}void RMQ_Init() {    for(int i = 0; i < n; i++) spt[i][0] = a[i];    for(int j = 1;; j++) {        int tmp = pow3(j);        if(tmp > n) break;        for(int i = 0; i + tmp <= n; i++)          spt[i][j] = max(max(spt[i][j-1], spt[i+tmp/3][j-1]), spt[i+2*tmp/3][j-1]);    }    }int RMQ(int l, int r) {    int k = log(r-l+1)/log(3);    int tmp = pow3(k);     int ans = max(spt[l][k], spt[r-tmp+1][k]);    if(r-l+1 > 2*tmp) ans = max(ans, spt[l+tmp][k]);//中间还有一段    return ans;}
原创粉丝点击