#include <stdio.h> #include <climits> #include <algorithm> #include <cstdlib> #include <map> using namespace std; int n; long long int sum = 0ll; long long int a; long long int in[501*1000]; map<long long int, long long int> lowest; map<long long int, long long int>::iterator it; long long int cur = 0ll, len = 0ll; void add(long long int npc, long long int npl) { long long int lowest_val = npl; it = lowest.find(npc); if(it != lowest.end()) { lowest_val = min(npl, it->second); lowest.erase(it); } lowest.insert({npc, lowest_val}); while(true) { it = lowest.find(npc); if(it != lowest.begin()) { --it; if(it->second >= lowest_val) { lowest.erase(it); } else { break; } } else { break; } } } long long int find_lowest_legal_l() { long long int ret = LLONG_MAX; it = lowest.lower_bound(0ll - cur); if(it != lowest.end()) { ret = it->second; } return ret; } int main() { scanf("%lld", &n); for(int i = 0; i < n; i++) { scanf("%lld", &a); sum += a; in[i] = a; } if(sum < 0ll) { printf("-1"); return 0; } add(in[0], 0ll); for(int i = 1; i < n; i++) { long long int l = find_lowest_legal_l(); if(l != LLONG_MAX) { // Yes, we can try to omit add(0ll-cur, l-1); } cur += in[i]; len++; } printf("%lld", find_lowest_legal_l() + len); return 0; }
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 | #include <stdio.h> #include <climits> #include <algorithm> #include <cstdlib> #include <map> using namespace std; int n; long long int sum = 0ll; long long int a; long long int in[501*1000]; map<long long int, long long int> lowest; map<long long int, long long int>::iterator it; long long int cur = 0ll, len = 0ll; void add(long long int npc, long long int npl) { long long int lowest_val = npl; it = lowest.find(npc); if(it != lowest.end()) { lowest_val = min(npl, it->second); lowest.erase(it); } lowest.insert({npc, lowest_val}); while(true) { it = lowest.find(npc); if(it != lowest.begin()) { --it; if(it->second >= lowest_val) { lowest.erase(it); } else { break; } } else { break; } } } long long int find_lowest_legal_l() { long long int ret = LLONG_MAX; it = lowest.lower_bound(0ll - cur); if(it != lowest.end()) { ret = it->second; } return ret; } int main() { scanf("%lld", &n); for(int i = 0; i < n; i++) { scanf("%lld", &a); sum += a; in[i] = a; } if(sum < 0ll) { printf("-1"); return 0; } add(in[0], 0ll); for(int i = 1; i < n; i++) { long long int l = find_lowest_legal_l(); if(l != LLONG_MAX) { // Yes, we can try to omit add(0ll-cur, l-1); } cur += in[i]; len++; } printf("%lld", find_lowest_legal_l() + len); return 0; } |