Codeforces 1405B #668Div2B

topic

Insert picture description here

answer

Two variables:

  1. Record the sum of positive numbers: initialize it to 0, add the positive number when it encounters a positive number; add it when it encounters a negative number, if the sum is positive, continue, if the sum is negative, set the variable to 0, and set the result The result is added to the negative sum.
  2. Record the negative sum.

AC code

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<string>
#include<queue>
#include<map>
#include<stack>
#include<list>
#include<set>
#include<deque>
#include<vector>
#include<ctime>

using namespace std;
//#pragma GCC optimize(2)
#define IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define ull unsigned long long
#define ll long long
#define rep(i, x, y) for(int i=x;i<=y;i++)
#define mms(x, n) memset(x, n, sizeof(x))
#define mmc(A, tree) memcpy(A, tree, sizeof(tree))
#define eps (1e-8)
#define PI (acos(-1.0))
#define INF (0x3f3f3f3f)
#define mod (ull)(1e9+7)
typedef pair<int, int> P;

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
#endif
    int T;
    scanf("%d", &T);
    while (T--) {
        ll p = 0, q = 0;
        ll t;
        int n;
        scanf("%d", &n);
        rep(i, 1, n) {
            scanf("%lld", &t);
            if (t > 0) {
                p += t;
            } else if (t < 0) {
                if (p == 0) q += t;
                else if (p + t > 0) p += t;
                else if (p + t <= 0) {
                    q += (p + t);
                    p = 0;
                }
            }
        }
        printf("%lld\n", -q);
    }
    return 0;
}

Off topic

At first it was more complicated to think about: first add up all consecutive positive numbers, then add up all consecutive negative numbers, then look for a positive number, and sum with the negative number after it. Repeat this step until there are only two digits or 0 left. Get the answer.
I encountered a lot of problems in the implementation process, and later found that it didn't need to be so troublesome. Two variables could be solved. Looking at the thinking at the time, it was really-I didn't wake up hhhh.

Guess you like

Origin blog.csdn.net/qq_45934120/article/details/108449244