洛谷P1816 忠诚 题解
洛谷P1816 忠诚 题解
题目链接:P1816 忠诚
题目描述:
老管家是一个聪明能干的人。他为财主工作了整整 \(10\) 年。财主为了让自己账目更加清楚,要求管家每天记 \(k\) 次账。由于管家聪明能干,因而管家总是让财主十分满意。
但是由于一些人的挑拨,财主还是对管家产生了怀疑。于是他决定用一种特别的方法来判断管家的忠诚。他把每次的账目按 \(1, 2, 3, \ldots\) 编号,然后不定时地问管家这样的问题:在 \(a\) 到 \(b\) 号账中最少的一笔是多少?
为了让管家没时间作假,他总是一次问多个问题。
输入格式:
第一行输入两个数 \(m, n\),表示有 \(m\) 笔账和 \(n\) 个问题。
第二行输入 \(m\) 个数,分别表示账目的钱数 \(x_i\)。
接下来 \(n\) 行分别输入 \(n\) 个问题,每行 \(2\) 个数字,分别表示开始的账目编号 \(a\) 和结束的账目编号 \(b\)。
输出格式:
第一行输出每个问题的答案,每个答案中间以一个空格分隔。
数据范围:
对于 \(100\%\) 的数据,\(1 \leq m \leq 10^5\),\(1 \leq n \leq 10^5\),\(0 \le x_i \le 10^5\)。
BIT写法也就图一乐(其实不建议)
主要在询问上有些区别,
例如如果 x-lowbit(x) 小于 \(l\) ,则此时不能直接
x-=lowbit(x)
因为这样会把 \([l,r]\) 之外的东西给弄进来,所以这部分直接暴力处理
复杂度不清楚,应该还是 \(O(\log n)\)
代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iomanip>
#include <random>
using namespace std;
#define int long long
#define INF 0x3f3f3f3f3f3f3f3f
#define N (int)(1e6+15)
int n,m,a[N],tree[N];
int lowbit(int x){return x&(-x);}
void update(int x,int v)
{
for(; x<=n; x+=lowbit(x))
tree[x]=min(tree[x],v);
}
int qMin(int l,int r)
{
int x=r,mn=INF;
for(; x>=l;)
{
if(x-lowbit(x)>l)
{
mn=min(mn,tree[x]);
x-=lowbit(x);
}
else mn=min(mn,a[x]),--x;
}
return mn;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
// freopen("check.in","r",stdin);
// freopen("check.out","w",stdout);
memset(tree,0x3f,sizeof(tree));
cin >> n >> m;
for(int i=1; i<=n; i++)
{
cin >> a[i];
update(i,a[i]);
}
for(int i=1,l,r; i<=m; i++)
{
cin >> l >> r;
cout << qMin(l,r) << ' ';
}
return 0;
}
本博客所有文章除特别声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 Q779’s Blog!




