-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
79 lines (72 loc) · 2.41 KB
/
main.cpp
File metadata and controls
79 lines (72 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Source: https://leetcode.com/problems/xor-after-range-multiplication-queries-i
// Title: XOR After Range Multiplication Queries I
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// You are given an integer array `nums` of length `n` and a 2D integer array `queries` of size `q`, where `queries[i] = [l_i, r_i, k_i, v_i]`.
//
// For each query, you must apply the following operations in order:
//
// - Set `idx = l_i`.
// - While `idx <= r_i`:
// - Update: `nums[idx] = (nums[idx] * v_i) % (10^9 + 7)`.
// - Set `idx += k_i`.
//
// Return the **bitwise XOR** of all elements in `nums` after processing all queries.
//
// **Example 1:**
//
// ```
// Input: nums = [1,1,1], queries = [[0,2,1,4]]
// Output: 4
// Explanation:
// - A single query `[0, 2, 1, 4]` multiplies every element from index 0 through index 2 by 4.
// - The array changes from `[1, 1, 1]` to `[4, 4, 4]`.
// - The XOR of all elements is `4 ^ 4 ^ 4 = 4`.
// ```
//
// **Example 2:**
//
// ```
// Input: nums = [2,3,1,5,4], queries = [[1,4,2,3],[0,2,1,2]]
// Output: 31
// Explanation:
// - The first query `[1, 4, 2, 3]` multiplies the elements at indices 1 and 3 by 3, transforming the array to `[2, 9, 1, 15, 4]`.
// - The second query `[0, 2, 1, 2]` multiplies the elements at indices 0, 1, and 2 by 2, resulting in `[4, 18, 2, 15, 4]`.
// - Finally, the XOR of all elements is `4 ^ 18 ^ 2 ^ 15 ^ 4 = 31`.
// ```
//
// **Constraints:**
//
// - `1 <= n == nums.length <= 10^3`
// - `1 <= nums[i] <= 10^9`
// - `1 <= q == queries.length <= 10^3`
// - `queries[i] = [l_i, r_i, k_i, v_i]`
// - `0 <= l_i <= r_i < n`
// - `1 <= k_i <= n`
// - `1 <= v_i <= 10^5`
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <vector>
using namespace std;
// Simulation
class Solution {
constexpr static int64_t modulo = 1e9 + 7;
public:
int xorAfterQueries(vector<int>& nums, const vector<vector<int>>& queries) {
// Loop
for (const auto& query : queries) {
const int l = query[0], r = query[1], k = query[2];
const int64_t v = query[3];
for (int i = l; i <= r; i += k) {
nums[i] = (nums[i] * v) % modulo;
}
}
// XOR
int ans = 0;
for (const int num : nums) {
ans ^= num;
}
return ans;
}
};