Skip to content

Commit 9109d77

Browse files
Add files via upload
1 parent 2832572 commit 9109d77

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
Firstly, we need to print the modified array not just print the number of changes required.
2+
3+
So, we will keep track of the positions of each index of modulus.
4+
5+
That is we will know the indices of all the A[i]%m = x,
6+
7+
---------------------
8+
9+
Now, we will make a pass from i = 0 to m - 1
10+
11+
If any modulus occurs more than N/m times, then we will remove the excess indices and put them in 'extra'
12+
13+
If any modulus occurs less than N/m times, we will remove from extra from the end [Since the ones in the end will be closer to the current modulus.] and put it here.
14+
15+
We need to do two passes, not one. (This is an unusual feature of this problem.)
16+
17+
Because The first element might be deficient and the last may be in excess.
18+
19+
-----------------------------
20+
long long no_of_changes = 0;
21+
vector <int> extra;
22+
23+
for(int runs = 1; runs <= 2; runs++)
24+
{
25+
for(int i = 0; i < m; i++)
26+
{
27+
while(position[i].size() > target)
28+
{
29+
int index = position[i].back();
30+
31+
extra.push_back(index);
32+
33+
position[i].pop_back();
34+
}
35+
36+
while(position[i].size() < target && extra.size() > 0)
37+
{
38+
int index = extra.back();
39+
40+
no_of_changes += (A[index]%m < i ? i - A[index]%m : m - A[index]%m + i);
41+
42+
A[index] += (A[index]%m < i ? i - A[index]%m : m - A[index]%m + i);
43+
44+
position[i].push_back(index);
45+
46+
extra.pop_back();
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)