1 条题解
-
0
方法思路
要解决这个问题,我们需要找到所有满足条件的区间,其中数组a和数组b在对应区间的每个位置上的数字都不同。我们可以使用滑动窗口的方法来高效地统计这些区间。
- 滑动窗口法:维护一个窗口,确保窗口内的所有位置都满足a[i] != b[i]。如果遇到不满足的位置,则调整窗口的起始位置。
- 统计有效区间:每次扩展窗口时,计算新增的有效区间数目。例如,窗口从[l, r]扩展到[l, r+1],新增的有效区间数目为r - l + 1。
代码实现
Java
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] a = new int[n]; int[] b = new int[n]; StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(st.nextToken()); } st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { b[i] = Integer.parseInt(st.nextToken()); } long count = 0; int left = 0; for (int right = 0; right < n; right++) { if (a[right] == b[right]) { left = right + 1; } else { count += right - left + 1; } } System.out.println(count); } }
Python
n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) count = 0 left = 0 for right in range(n): if a[right] == b[right]: left = right + 1 else: count += right - left + 1 print(count)
C++
#include <iostream> #include <vector> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector<int> a(n), b(n); for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = 0; i < n; i++) { cin >> b[i]; } long long count = 0; int left = 0; for (int right = 0; right < n; right++) { if (a[right] == b[right]) { left = right + 1; } else { count += right - left + 1; } } cout << count << endl; return 0; }
- 1
信息
- ID
- 31
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 4
- 标签
- 递交数
- 1
- 已通过
- 1
- 上传者