fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int MAXN = 100000;
  5. int arr[MAXN];
  6. int tree[4*MAXN];
  7.  
  8. // Hàm gcd có sẵn trong <algorithm> (C++17) là std::__gcd(x, y);
  9.  
  10. void build_tree(int index, int start, int end) {
  11. if (start == end) {
  12. tree[index] = arr[start];
  13. return;
  14. }
  15. int mid = (start + end) / 2;
  16. build_tree(index*2, start, mid);
  17. build_tree(index*2+1, mid+1, end);
  18. tree[index] = std::__gcd(tree[index*2], tree[index*2+1]);
  19. }
  20.  
  21. int get_gcd(int index, int start, int end, int L, int R) {
  22. if (end < L || start > R) return 0; // segment hoàn toàn ngoài [L, R]
  23. if (L <= start && end <= R) return tree[index]; // segment nằm gọn trong [L, R]
  24. int mid = (start + end) / 2;
  25. int gcdLeft = get_gcd(index*2, start, mid, L, R);
  26. int gcdRight = get_gcd(index*2+1, mid+1, end, L, R);
  27. return std::__gcd(gcdLeft, gcdRight);
  28. }
  29.  
  30. int main() {
  31. ios::sync_with_stdio(false);
  32. cin.tie(nullptr);
  33.  
  34. int n, k;
  35. cin >> n >> k;
  36. for (int i = 0; i < n; i++) {
  37. cin >> arr[i];
  38. }
  39.  
  40. // Xây cây segment
  41. build_tree(1, 0, n-1);
  42.  
  43. int ans = 1;
  44. for (int start = 0; start <= n-k; start++) {
  45. int g = get_gcd(1, 0, n-1, start, start + k - 1);
  46. ans = max(ans, g);
  47. }
  48.  
  49. cout << ans << "\n";
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0.01s 5284KB
stdin
10 3
2 6 4 3 18 12 24 8 7 5

stdout
6