思路:
使用ST表。ST表求区间最大值改为按位或即可。
ST模板可参考MT3024 max=min
代码:
1.暴力6/10
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
const int M = 5e5 + 10;
int n, m;
int num[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
cin >> num[i];
}
int l, r;
for (int i = 1; i <= m; i++)
{
cin >> l >> r;
int ans = num[l];
for (int j = l + 1; j <= r; j++)
{
ans = ans | num[j];
}
cout << ans << endl;
}
}
2.ST表:
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
const int M = 5e5 + 10;
int n, m;
int mn[N][50], Lg[N], a[N];
void pre()
{
Lg[1] = 0;
for (int i = 2; i <= n; i++)
{
Lg[i] = Lg[i >> 1] + 1;
}
}
void ST_create()
{ // 创建ST表
for (int i = 1; i <= n; i++)
{
mn[i][0] = a[i];
}
for (int j = 1; j <= Lg[n]; j++)
{
for (int i = 1; i <= n - (1 << j) + 1; i++)
{
mn[i][j] = (mn[i][j - 1] | mn[i + (1 << (j - 1))][j - 1]); // 改成或运算
}
}
}
int ST_q(int l, int r)
{ // ST表求区间或
int k = Lg[r - l + 1];
return (mn[l][k] | mn[r - (1 << k) + 1][k]); // 改成或运算
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
}
pre();
ST_create();
int l, r;
for (int i = 1; i <= m; i++)
{
cin >> l >> r;
cout << ST_q(l, r) << endl;
}
}