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
| class Solution { private: vector<int> nums; struct node { long long val = 0; int lazytag = 0; }; vector<node> tree; void buildtree(int root, int start, int end) { if (start == end) { tree[root].val = nums[start]; return; } int leftroot = root * 2; int rightroot = root * 2 + 1; int mid = (start + end) / 2; buildtree(leftroot, start, mid); buildtree(rightroot, mid + 1, end); tree[root].val = tree[leftroot].val + tree[rightroot].val; } void update(int root, int start, int end, int l, int r, int k) { if (l > end || r < start) return; int leftroot = root * 2; int rightroot = root * 2 + 1; int mid = (start + end) / 2; if (l <= start && r >= end) { tree[root].val += (end - start + 1) * k; tree[root].lazytag += k; return; } if (tree[root].lazytag != 0) { tree[leftroot].lazytag += tree[root].lazytag; tree[leftroot].val += (mid - start + 1) * tree[root].lazytag; tree[rightroot].lazytag += tree[root].lazytag; tree[rightroot].val += (end-mid) * tree[root].lazytag; tree[root].lazytag = 0; } update(leftroot, start, mid, l, r, k); update(rightroot, mid + 1, end, l, r, k); tree[root].val = tree[leftroot].val + tree[rightroot].val; } long long query(int root, int start, int end, int l, int r) { if (l > end || r < start) return 0; int leftroot = root * 2; int rightroot = root * 2 + 1; int mid = (start + end) / 2; if (l <= start && r >= end) return tree[root].val; if (tree[root].lazytag != 0) { tree[leftroot].lazytag += tree[root].lazytag; tree[leftroot].val += (long long)(mid - start + 1) * tree[root].lazytag; tree[rightroot].lazytag += tree[root].lazytag; tree[rightroot].val += (long long)(end-mid) * tree[root].lazytag; tree[root].lazytag = 0; } long long res = query(leftroot, start, mid, l, r) + query(rightroot, mid + 1, end, l, r); tree[root].val = tree[leftroot].val + tree[rightroot].val; return res; }
public: vector<int> corpFlightBookings(vector<vector<int>>& bookings, int n) { nums.resize(n,0); tree.resize(n * 4); buildtree(1, 0, n-1); for (int i = 0; i < bookings.size(); i++) { update(1, 1, n, bookings[i][0], bookings[i][1], bookings[i][2]); } vector<int> res; for (int i = 1; i <= n; i++) { res.push_back(query(1, 1, n, i, i)); } return res; } };
|