cf 1548B - Integers Have Friends
爽了 过了
https://codeforces.com/problemset/problem/1548/B
题意: 给一段序列, 求满足存在某数使得区间全部元素同余的最长连续子序列的长度。
做法 : 容易想到先转化为差分数组(满足条件的子序列的元素都为 a = mx + y),然后就变成求最长的区间gcd大于 1 的区间长度
预处理能快速得到一段区间的gcd的查询,可以写线段树 也可以写st表, 然后固定左端点,得到满足条件的最大右端点。
可以有(线段树 + st表)*(二分 + 双指针)这些方法。
当然是选最简单的 st表 + 双指针 啦, 不然对不起它1800的难度。
而且时间复杂度也比较保险
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5+10;
ll st[N][20];
int n;
ll a[N];
int ans[N];
ll exgcd(ll a, ll b, ll& x, ll& y) {
if(!b) {
x = 1, y = 0;
return a;
}
ll res = exgcd(b, a%b, y, x);
y -= a/b * x;
return res;
}
int getst() {
int len = log(n) / log(2) + 1;
for(int i = 1; i <= n; i++) st[i][0] = a[i];
ll x, y;
for(int j = 1; j <= len; j++) {
for(int i = 1; i + (1<<(j-1)) <= n; i++) {
st[i][j] = exgcd(st[i][j-1], st[i + (1 << (j-1))][j-1], x, y);
}
}
return len;
}
void initst(int len) {
for(int i = 1; i <= n; i++)
for(int j = 0; j <= len; j++) st[i][j] = 0;
}
int solve() {
for(int i = 1; i <= n; i++) ans[i] = 0;
int bit = getst();
ll x, y;
for(int i = 1, j = 1; i <= j && i <= n && j <= n; ) {
int len = log(j - i + 1) / log(2);
while(exgcd(st[i][len], st[j - (1 << len) + 1][len], x, y) > 1 && j <= n) {
ans[i] = max(ans[i], j - i + 1);
j ++;
len = log(j - i + 1) / log(2);
}
i++;
if(j < i) j++;
}
int res = max(1, ans[1]);
for(int i = 2; i <= n; i++) res = max(res, ans[i] + 1);
initst(bit);
return res;
}
int main() {
int T;
scanf("%d", &T);
while(T -- ) {
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%lld", &a[i]);
for(int i = n; i >= 1; i--) a[i] = abs(a[i] - a[i-1]);
printf("%d\n", solve());
}
return 0;
}