#include <bits/stdc++.h>
using namespace std;
int n;
int ile_m;
int tab[500002];
vector <pair <pair <int, int>, int>> sciezka;
vector <int> decyzje;
int mini = 1000000;
void rek(int x, long long suma, int dl){
// cout << x << "\n";
if (x == (int)sciezka.size()){
if (suma >= 0) mini = min(mini, dl);
// cout << mini << "\n";
if (mini == ile_m) exit(0);
return;
}
if (suma >= 0){
decyzje.push_back(0);
rek(x + 1, 1LL * tab[sciezka[x].first.second], dl);
decyzje.pop_back();
}
decyzje.push_back(1);
rek(x + 1, suma + 1LL * tab[sciezka[x].first.second], dl + sciezka[x].second);
decyzje.pop_back();
return;
}
int main (){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n;
long long s = 0;
int l = -1;
for (int i = 0; i < n; i ++){
cin >> tab[i];
s += 1LL * tab[i];
if (tab[i] != 0){
if (l != -1) sciezka.push_back({{l, i}, i - l});
l = i;
if (tab[i] < 0) ile_m ++;
}
}
if (s < 0){
cout << -1 << "\n";
return 0;
}
if (sciezka.empty()){
cout << 0 << "\n";
return 0;
}
rek(0, 1LL * tab[sciezka[0].first.first], 0);
cout << mini << "\n";
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | #include <bits/stdc++.h> using namespace std; int n; int ile_m; int tab[500002]; vector <pair <pair <int, int>, int>> sciezka; vector <int> decyzje; int mini = 1000000; void rek(int x, long long suma, int dl){ // cout << x << "\n"; if (x == (int)sciezka.size()){ if (suma >= 0) mini = min(mini, dl); // cout << mini << "\n"; if (mini == ile_m) exit(0); return; } if (suma >= 0){ decyzje.push_back(0); rek(x + 1, 1LL * tab[sciezka[x].first.second], dl); decyzje.pop_back(); } decyzje.push_back(1); rek(x + 1, suma + 1LL * tab[sciezka[x].first.second], dl + sciezka[x].second); decyzje.pop_back(); return; } int main (){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; long long s = 0; int l = -1; for (int i = 0; i < n; i ++){ cin >> tab[i]; s += 1LL * tab[i]; if (tab[i] != 0){ if (l != -1) sciezka.push_back({{l, i}, i - l}); l = i; if (tab[i] < 0) ile_m ++; } } if (s < 0){ cout << -1 << "\n"; return 0; } if (sciezka.empty()){ cout << 0 << "\n"; return 0; } rek(0, 1LL * tab[sciezka[0].first.first], 0); cout << mini << "\n"; } |
English