Answer the question
In order to leave comments, you need to log in
Why can't it be solved with a greedy algorithm?
There is a challenge: https://codeforces.com/contest/1400/problem/E
My code:
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int main() {
IOS;
int n;
cin >> n;
vector<int>a;
a.resize(n);
for (int i = 0; i < n; i++) cin >> a[i];
int len = 0;
// int not1 = 0;
//int y1 = 0;
long long ans = 0;
bool f = false;
a.push_back(0);
for (int i = 0; i <= n; i++) {
if (a[i] == 0) {
if (len > 1) {
ans += 1;
for (int j = i - len; j < i; j++) {
a[j]--;
}
}
//ans += len;
len = 0;
f = false;
}
else {
if (f && a[i]>1) {
ans += 2; len = 0;
a[i] = 0;
a[i - 1] = 0;
}
else len++;
if (a[i] > 1) f = true;
else f = false;
// if (a[i] == 1) y1++;
// else not1++;
}
}
for (int i = 0; i < n; i++) {
if (a[i] > 0) ans++;
}
cout << ans << "\n";
}
if (f && a[i]>1) {
ans += 2; len = 0;
a[i] = 0;
a[i - 1] = 0;
}
Answer the question
In order to leave comments, you need to log in
Why doesn't greed work? You yourself brought a test on which such greed does not work.
I can give you an example. In {1, 2, 3, 2, 1} - the answer is 3. Here you need to delete the segment 1..5, then 2..4, then 1 occurrence of element 3, If the form is slightly different, for example {1, 100, 1000, 100, 1} - then the answer is 4. After the first deletion of the segment, you must delete the numbers one by one.
In general, a greedy solution does not work until proven otherwise.
One of your observations is indeed true - in the optimal solution, some segments are removed first, and then the entire remaining elements are removed one at a time.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question