I was trying [problem:1692E] using C++, I am getting WA on test 2. Submission: [submission:359959283]↵
↵
Logic:↵
I have stored the amount of operations it would take to remove the '1' on every index from left end of the array in one vector `v1` and from the right side of the array in another vector `v2`. Then I have calculated the number of '1's to be removed in `d`. I iterated till `d = 0` to get the nearest '1' from each end of the vector by using `f` and `b` to store the amount of elements removed already from left and right side of the vector respectively. While iterating, I have added the least amount of operations from each end to `r` and at last, printed `r`.↵
↵
Please tell me what is wrong with the logic and the code↵
↵
Code:↵
↵
~~~~~↵
#include <bits/stdc++.h>↵
using namespace std;↵
↵
void solve() {↵
int n, s;↵
cin >> n >> s;↵
vector<int> v1, v2;↵
for (int i = 0; i < n; i++) {↵
int a;↵
cin >> a;↵
if (a == 1) {↵
v1.push_back(i + 1);↵
v2.push_back(n - i);↵
}↵
}↵
int d = v1.size() - s, r = 0, f = 0, b = 0;↵
if (d < 0) cout << -1 << endl;↵
else {↵
while (d != 0) {↵
if (v1[0] - f < v2[v2.size() - 1] - b) {↵
r += v1[0] - f;↵
f = v1[0];↵
v1.erase(v1.begin());↵
v2.erase(v2.begin());↵
} else {↵
r += v2[v2.size() - 1] - b;↵
b = v2[v2.size() - 1];↵
v1.pop_back();↵
v2.pop_back();↵
}↵
d--;↵
}↵
cout << r << endl;↵
}↵
}↵
↵
int main() {↵
int t = 1;↵
cin >> t;↵
while (t--) solve();↵
}↵
~~~~~↵
↵
↵
Logic:↵
I have stored the amount of operations it would take to remove the '1' on every index from left end of the array in one vector `v1` and from the right side of the array in another vector `v2`. Then I have calculated the number of '1's to be removed in `d`. I iterated till `d = 0` to get the nearest '1' from each end of the vector by using `f` and `b` to store the amount of elements removed already from left and right side of the vector respectively. While iterating, I have added the least amount of operations from each end to `r` and at last, printed `r`.↵
↵
Please tell me what is wrong with the logic and the code↵
↵
Code:↵
↵
~~~~~↵
#include <bits/stdc++.h>↵
using namespace std;↵
↵
void solve() {↵
int n, s;↵
cin >> n >> s;↵
vector<int> v1, v2;↵
for (int i = 0; i < n; i++) {↵
int a;↵
cin >> a;↵
if (a == 1) {↵
v1.push_back(i + 1);↵
v2.push_back(n - i);↵
}↵
}↵
int d = v1.size() - s, r = 0, f = 0, b = 0;↵
if (d < 0) cout << -1 << endl;↵
else {↵
while (d != 0) {↵
if (v1[0] - f < v2[v2.size() - 1] - b) {↵
r += v1[0] - f;↵
f = v1[0];↵
v1.erase(v1.begin());↵
v2.erase(v2.begin());↵
} else {↵
r += v2[v2.size() - 1] - b;↵
b = v2[v2.size() - 1];↵
v1.pop_back();↵
v2.pop_back();↵
}↵
d--;↵
}↵
cout << r << endl;↵
}↵
}↵
↵
int main() {↵
int t = 1;↵
cin >> t;↵
while (t--) solve();↵
}↵
~~~~~↵
↵



