思路:
使用ST表。ST表模板可参考MT3024 max=min
注意点:此题范围较大,所以要避免超时。
①使用 ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); 加快输入输出速度。
②换行使用'\n'而不是endl
代码:
1.暴力6/8
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
const int M = 4e6 + 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 = 4e6 + 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()
{ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);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) << '\n';}
}