洛谷P1816 忠诚

题目来源https://www.luogu.org/problem/show?pid=1816


RMQ问题。


anc[i][k]记录第i个数往前2^k的数的编号。


lcs[i][k]记录从第i-2^k个数到第i个数之间的最小值。


更新时anc[x][i]=anc[anc[x][i-1]][i-1],lcs[x][i]=min(lcs[x][i-1],lcs[anc[x][i-1]][i-1])


#include <algorithm>
#include <iostream>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <string>
#include <cstdio>
#include <cctype>
#include <vector>
#include <ctime>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
const int maxn=1e5+1;
const int maxh=20;
int n,m;
long long a[maxn];
long long anc[maxn][maxh]={0};
long long lcs[maxn][maxh]={0};
void dfs()
{
    for(int i=0;i<maxh;i++)
    {
        anc[1][i]=1;
        lcs[1][i]=a[1];
    }
    for(int x=1;x<=n;x++)
    {
        for(int i=1;i<maxh;i++)
        {
            anc[x][i]=anc[anc[x][i-1]][i-1];
            lcs[x][i]=min(lcs[x][i-1],lcs[anc[x][i-1]][i-1]);
        }
        anc[x+1][0]=x;
        lcs[x+1][0]=min(a[x+1],a[x]);
    }
}
long long swim(int x,int h)
{
    long long tot=9e10;
    for(int i=0;h>0;i++)
    {
        if(h&1)
        {
            tot=min(tot,lcs[x][i]);
            x=anc[x][i];
        }
        h=(h>>1);
    }
    return tot;
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m;
    for(int i=1;i<=n;i++)cin>>a[i];
    dfs();
    for(int i=1;i<=m;i++)
    {
        int x,y;cin>>x>>y;
        if(x>y)swap(x,y);
        if(x==y)cout<<a[x]<<" ";
        else cout<<swim(y,y-x)<<" ";
    }
    return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值