fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4.  
  5. #define MOD 1000000007
  6. #define MAXN 100005
  7.  
  8. int A[MAXN];
  9. double dp_log[MAXN];
  10. int predecessor[MAXN];
  11. int deque_indices[MAXN];
  12. int front, back;
  13.  
  14. int main() {
  15. int N, K;
  16. scanf("%d %d", &N, &K);
  17. for (int i = 0; i < N; i++) {
  18. scanf("%d", &A[i]);
  19. }
  20.  
  21. // Initialize for the first street (0-based index)
  22. dp_log[0] = log(A[0]);
  23. predecessor[0] = -1;
  24.  
  25. front = 0;
  26. back = -1;
  27. deque_indices[++back] = 0;
  28.  
  29. for (int i = 1; i < N; i++) {
  30. int s = (i - K) > 0 ? (i - K) : 0;
  31.  
  32. // Remove indices from the front that are out of the window
  33. while (front <= back && deque_indices[front] < s) {
  34. front++;
  35. }
  36.  
  37. // Get the minimum dp_log in the current window
  38. int min_j = deque_indices[front];
  39. dp_log[i] = dp_log[min_j] + log(A[i]);
  40. predecessor[i] = min_j;
  41.  
  42. // Maintain the deque by removing indices with higher or equal dp_log values
  43. while (front <= back && dp_log[i] <= dp_log[deque_indices[back]]) {
  44. back--;
  45. }
  46. deque_indices[++back] = i;
  47. }
  48.  
  49. // Calculate the product modulo MOD
  50. long long product = 1;
  51. int current = N - 1;
  52. while (current != -1) {
  53. product = (product * A[current]) % MOD;
  54. current = predecessor[current];
  55. }
  56.  
  57. printf("%lld\n", product);
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 0s 5288KB
stdin
4 2
1 2 3 4.
stdout
8