🍑 算法题解专栏
🍑 题目地址
输入
5 3
1 3 6 4 10
输出
5
🍑 前缀和 + 双指针版(AC)
import java.util.Scanner;
public class Main
{
static int N = 100010, n, d;
static int[] a = new int[N];
static int[] s = new int[N];
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
d = sc.nextInt();
for (int i = 1; i <= n; i++)
{
a[i] = sc.nextInt();
if (a[i] % d != 0)
s[i] = 1;// 初始化差分数组
}
// 预处理前缀和数组
for (int i = 1; i <= n; i++)
s[i] += s[i - 1];
long ans = 0;
for (int l = 1, r = 2; l < n; l++)// l 为左端点,r为右端点
{
while (r <= n && s[r] - s[l - 1] <= 1)
r++;
ans += r - (l + 1);
}
System.out.println(ans);
}
}
🙈 暴力双指针版(60%)
import java.util.Scanner;
public class Main
{
static int N = 100010, n, d;
static int[] a = new int[N];
static boolean check(int l, int r)
{
int cnt = 0;
for (int i = l; i <= r; i++)
if (a[i] % d != 0)
cnt++;
if (cnt > 1)
return false;
return true;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
d = sc.nextInt();
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
long ans = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
{
if (check(i, j))
{
// System.out.println(i + " " + j);
ans++;
} else
{
break;
}
}
System.out.println(ans);
}
}