-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiffernecearray
More file actions
89 lines (75 loc) · 1.82 KB
/
Copy pathDiffernecearray
File metadata and controls
89 lines (75 loc) · 1.82 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
80
81
82
83
84
85
86
87
88
89
//https://codeforces.com/group/c3FDl9EUi9/contest/262795/problem/F
//bruteforce
//O(n*k)
#include<iostream>
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
int main()
{
ll n,q;
cin>>n>>q;
vector<ll>v(n);
for(ll i = 0; i < n; i++)
{
cin>>v[i];
}
while(q--)
{
ll l,r,val;
cin>>l>>r>>val;
l-=1;
r-=1;
for(ll i = 0; i < n; i++)
{
if(i >= l && i <= r)
{
v[i]+=val;
}
}
}
for(int i = 0; i < n; i++)
{
cout<<v[i]<<" ";
}
}
///optimal using differnece array
#include <iostream>
#include <vector>
typedef long long ll;
using namespace std;
int main() {
ll n, q;
cin >> n >> q;
vector<ll> v(n); // Original array
vector<ll> diff(n + 1); // Difference array (size n+1 to handle edge cases)
// Reading the original array
for (ll i = 0; i < n; i++) {
cin >> v[i];
}
// Process each query
while (q--) {
ll l, r, val;
cin >> l >> r >> val;
// Adjust 1-indexed l, r to 0-indexed
l -= 1;
r -= 1;
// Apply the difference array technique
diff[l] += val; // Add `val` at the start of the range
if (r + 1 < n) {
diff[r + 1] -= val; // Subtract `val` after the end of the range
}
}
// Apply the difference array back to the original array
ll increment = 0; // Tracks the cumulative increment
for (ll i = 0; i < n; i++) {
increment += diff[i]; // Add the current difference to the increment
v[i] += increment; // Update the original array with the cumulative increment
}
// Output the final array
for (ll i = 0; i < n; i++) {
cout << v[i] << " ";
}
cout << endl;
return 0;
}