fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // max independent set on path [l, r]
  5. long long getMax(const vector<long long>& a, int l, int r) {
  6. if (l > r) return 0;
  7.  
  8. long long prev2 = 0, prev = 0;
  9. for (int i = l; i <= r; i++) {
  10. long long take = prev2 + a[i]; // can't use adjacent
  11. long long skip = prev;
  12. long long cur = max(take, skip);
  13. prev2 = prev;
  14. prev = cur;
  15. }
  16. return prev;
  17. }
  18.  
  19. int main() {
  20. ios::sync_with_stdio(false);
  21. cin.tie(nullptr);
  22.  
  23. int n;
  24. cin >> n;
  25.  
  26. vector<long long> a(n + 1);
  27. long long sum = 0;
  28. for (int i = 1; i <= n; i++) {
  29. cin >> a[i];
  30. sum += a[i];
  31. }
  32.  
  33. // min edge cover = sum - max independent set
  34. // for cycle: either skip first edge or take it
  35. long long skip1 = getMax(a, 2, n);
  36. long long take1 = a[1] + getMax(a, 3, n - 1);
  37. long long maxIS = max(skip1, take1);
  38.  
  39. cout << sum - maxIS << "\n";
  40. return 0;
  41. }
Success #stdin #stdout 0.01s 5308KB
stdin
Standard input is empty
stdout
0