ENG  RUSTimus Online Judge
Online Judge
Problems
Authors
Online contests
About Online Judge
Frequently asked questions
Site news
Webboard
Links
Problem set
Submit solution
Judge status
Guide
Register
Update your info
Authors ranklist
Current contest
Scheduled contests
Past contests
Rules
back to board

Discussion of Problem 1452. Pascal vs. C++

AC but memory is bad
Posted by coolboy19521 19 Oct 2024 00:56
How can I improve memory usage in this code?

#include "bits/stdc++.h"

using namespace std;

int main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    short n;
    cin >> n;

    vector<pair<int,short>> s(n, pair<int,int>());

    for (int i = 0; i < n; i ++) {
        cin >> s[i].first;
        s[i].second = i;
    }

    sort(begin(s),end(s));
    for (short i = 1; i < n; i ++) {
        if (s[i].first == s[i - 1].first) {
            s.erase(begin(s) + i);
            n --;
            i --;
        }
    }

    vector<vector<short>> dp(n + 1, vector<short>(n + 1, 0));

    for (short i = 1; i < n - 1; i ++) {
        short l = i - 1;
        short r = i + 1;
        while (0 <= l && r < n) {
            int dfl = s[i].first - s[l].first;
            int dfr = s[r].first - s[i].first;
            if (dfl == dfr) {
                dp[i][r] = dp[l][i] + 1;
                l --;
                r ++;
            } else if (dfl > dfr) {
                r ++;
            } else {
                l --;
            }
        }
    }

    if (1 == n) {
        cout << "1\n1\n";
    } else {
        short mx = -1;
        short di = 0;
        short dj = 0;

        for (int i = 0; i < n - 1; i ++) {
            for (int j = i + 1; j < n; j ++) {
                if (dp[i][j] >= mx) {
                    mx = dp[i][j];
                    di = i;
                    dj = j;
                }
            }
        }

        int df = s[dj].first - s[di].first;

        mx += 2;

        cout << mx << '\n';

        for (; -1 < di;) {
            cout << s[dj].second + 1 << ' ';
            dj = di;
            di = -1;
            for (short i = 0; i < dj; i ++) {
                if (s[dj].first - s[i].first == df) {
                    di = i;
                    break;
                }
            }
        }

        cout << s[dj].second + 1 << '\n';
    }
}