优化代码

学术版

nidiewojiadeluosi @ 2024-11-01 23:28:14

tle炸掉了

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;

inline ll read() {
    ll x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

int main() {
    int n = read();
    vector<ll> a(n), b(n), c(n);

    for (int i = 0; i < n; i++) a[i] = read();
    for (int i = 0; i < n; i++) b[i] = read();
    for (int i = 0; i < n; i++) c[i] = read();

    ll ans = 0;
    vector<ll> sum(n + 1, 0);  

    for (int i = 0; i < n; i++) {
        sum[i + 1] = sum[i] + a[i];
    }

    for (int l1 = 0; l1 < n; l1++) {

        for (int r1 = l1; r1 < n; r1++) {

            ll gain1 = 0;
            for (int i = l1; i <= r1; i++) {
                gain1 += b[i] - a[i];
            }

            for (int l2 = 0; l2 < n; l2++) {

                for (int r2 = l2; r2 < n; r2++) {
                    ll curr = sum[n];  

                    curr += gain1;

                    for (int i = l2; i <= r2; i++) {
                        if (i >= l1 && i <= r1) {

                            curr += c[i] - b[i];
                        } else {

                            curr += b[i] - a[i];
                        }
                    }

                    ans = max(ans, curr);
                }
            }
        }
    }

    printf("%lld\n", ans);
    return 0;
}

by shawn0618 @ 2024-11-01 23:30:22

@nidiewojiadeluosi 你这是啥题啊?


by nidiewojiadeluosi @ 2024-11-01 23:36:58

@shawn0618 dp


by shawn0618 @ 2024-11-02 09:08:58

@nidiewojiadeluosi 。。。

啥dp


by shawn0618 @ 2024-11-02 09:09:32

你告诉我算法,不告诉我数据范围我咋测啊


by nidiewojiadeluosi @ 2024-11-02 11:13:02

@shawn0618 对不起,ai,bi,ci<=是10^9. n<=2*10^5


by shawn0618 @ 2024-11-02 17:40:33

两层循环不炸就怪了呢。

发一下原题目。


|