fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long int ll;
  4.  
  5. int main() {
  6. // Optimize standard I/O operations for speed
  7. ios_base::sync_with_stdio(false);
  8. cin.tie(NULL);
  9.  
  10. ll t;
  11. cin >> t;
  12. while (t--) {
  13. ll m, n;
  14. cin >> m >> n;
  15.  
  16. vector<int> b(n + 1);
  17. ll total_1 = 0, total_2 = 0;
  18. ll r1 = 0, r5 = 0;
  19.  
  20. // Pass 1: Read array and calculate initial sums for index 1
  21. for (ll i = 1; i <= n; i++) {
  22. cin >> b[i];
  23. if (b[i] == 1 || b[i] == 3) {
  24. total_1++;
  25. r1 += (i - 1); // Distance from index 1
  26. }
  27. if (b[i] == 2 || b[i] == 3) {
  28. total_2++;
  29. r5 += (i - 1); // Distance from index 1
  30. }
  31. }
  32.  
  33. ll left_1 = 0, left_2 = 0;
  34.  
  35. // Pass 2: Calculate for each index i by shifting the reference point
  36. for (ll i = 1; i <= n; i++) {
  37. cout << abs(r1 - r5) << " ";
  38.  
  39. // Update the count of elements seen so far (<= i)
  40. if (b[i] == 1 || b[i] == 3) left_1++;
  41. if (b[i] == 2 || b[i] == 3) left_2++;
  42.  
  43. // Shifting index from i to i+1:
  44. // Elements on the left increase distance by 1, elements on the right decrease by 1
  45. r1 += 2 * left_1 - total_1;
  46. r5 += 2 * left_2 - total_2;
  47. }
  48. cout << "\n";
  49. }
  50.  
  51. return 0;
  52. }
Success #stdin #stdout 0s 5284KB
stdin
2
1 5
2 1 3 0 1
1 8
1 1 3 0 2 0 3 3
stdout
5 2 1 0 1 
3 2 1 4 7 8 9 10