跳到正文

题解

AT_abc397_c [ABC397C] Variety Split Easy 题解

原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟

版本

  1. v1当前

题意简述

一个长度为 nn 的序列 {ai}\{a_i\},对于每个 ii,你需要求出 ansians_i 表示 a1∼a1a_1 \sim a_1 中不同数字的数量以及 ai+1∼ana_{i + 1} \sim a_n 中不同数字的数量。

最后输出 max⁡i=1nansi\displaystyle \max_{i = 1}^{n} ans_i。

开始解题

很简单的一道题目。

由于我们要求的区间是 a1∼aia_1 \sim a_i 和 ai+1∼ana_{i + 1} \sim a_n,这可以看成一个前缀和一个后缀。

而对于一个前缀去求不同数字的数量是简单的;设 preipre_i 表示 a1∼aia_1 \sim a_i 不同数字的数量,可以开一个 map 记录当前的 aia_i 是否出现过,若没出现过,则 prei=prei−1+1pre_i = pre_{i - 1} + 1,并标记 aia_i 出现过。反之 prei=prei−1pre_i = pre_{i - 1},表示没有增加。

对于后缀实际上是同理的,设 sufisuf_i 表示 ai∼ana_i \sim a_n 不同数字的数量,仍然可以使用 map 来记录数字是否出现过。若没出现过,就 sufi=sufi+1+1suf_i = suf_{i + 1} + 1,并打上标记。反之 sufi=sufi+1suf_i = suf_{i + 1}

而最后可以发现 ansi=prei+sufi+1ans_i = pre_i + suf_{i + 1},记录一下然后取个最大值就是简单的,总的时间复杂度为 O(nlog⁡n)O(n \log n),因为 map 有一只 log⁡\log,当然做到 O(n)O(n) 也是简单的。把 map 换为 unordered_map 或者直接哈希都行。反正都能过。

最后上个代码。

code :

C++
#include <bits/stdc++.h>
#define ll long long
#define db double
#define vec vector
#define pll pair<ll, ll>
#define mkp make_pair
#define endl "\n"

using namespace std;

const ll mod = 998244353;

namespace fastio {
    char buf[1 << 21], *p1 = buf, *p2 = buf;

    const ll getc() {
        return p1 == p2 && ( p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1 ++;
    }

    const ll read() {
        ll x = 0, f = 1;

        char ch = getc();

        while (ch < '0' || ch > '9') {
            if (ch == '-') f = -1; ch = getc();
        }

        while (ch >= '0' && ch <= '9') {
            x = (x << 1) + (x << 3) + (ch ^ 48), ch = getc();
        }

        return x * f;
    }

    const void write(ll x) {
        if (x < 0) {
            putchar('-'), x = -x;
        }

        ll sta[35], top = 0;

        do {
            sta[top++] = x % 10, x /= 10;
        } while (x);

        while (top) putchar(sta[--top] + 48);
    }
}

#define rd fastio::read
#define wt fastio::write
#define gc fastio::getc

ll n, m, q, a[300005], pre[300005], suf[300005]; string s;

ll opt, l, r, ans = 0;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    ll i, j, k, x, y, z, res = 0, now;

    n = rd();

    for (i = 1; i <= n; i++) {
        a[i] = rd();
    }

    map<ll, bool> Map1, Map2;

    for (i = 1; i <= n; i++) {
        if (!Map1[a[i]]) {
            Map1[a[i]] = 1, pre[i] = pre[i - 1] + 1;
        } else {
            pre[i] = pre[i - 1];
        }
    }

    for (i = n; i; i--) {
        if (!Map2[a[i]]) {
            Map2[a[i]] = 1, suf[i] = suf[i + 1] + 1;
        } else {
            suf[i] = suf[i + 1];
        }
    }

    for (i = 1; i <= n; i++) {
        ans = max(ans, pre[i] + suf[i + 1]);
    }

    wt(ans);

    return 0;
}

AC record

原文