思路:
ST表,ST表模板可参考MT3024 max=min
注意,这里使用快读快写避免超时
代码:
cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n, m, a[N], mn[N][20], Lg[N], l, r, ans;
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] = gcd(mn[i][j - 1], mn[i + (1 << (j - 1))][j - 1]);
}
}
}
int ST_qgcd(int l, int r)
{ // ST表求gcd
int k = Lg[r - l + 1];
return gcd(mn[l][k], mn[r - (1 << k) + 1][k]);
}
// 快读快写:
int read()
{
int ret = 0;
char ch = getchar();
while (ch < '0' || ch > '9')
ch = getchar();
while (ch >= '0' && ch <= '9')
{
ret = ret * 10 + ch - '0';
ch = getchar();
}
return ret;
}
void write(int x)
{
if (x >= 10)
write(x / 10);
putchar(x % 10 + '0');
}
int main()
{
n = read(), m = read();
for (int i = 1; i <= n; i++)
a[i] = read();
pre();
ST_create();
while (m--)
{
l = read(), r = read();
ans = ST_qgcd(l, r);
write(ans);
putchar('\n');
}
return 0;
}