chenfy27的刷题记录

导航

abc295D 统计由SS构成的子串个数

题面:给出长为n的数字串,问它存在多少个子串是happy串?happy串指经重排后,可以写成一个串重复2次得到的形式,例如串11223344,重排后能得到12341234,为1234重复2次的结果,因此是happy串。
范围:1<=n<=5e5

分析:哈希判断是否相同,只需要判断各个数字出现的奇偶性即可。

#include <bits/stdc++.h>
using i64 = long long;

struct node {
    int cnt[10];
    node() {
        for (int i = 0; i < 10; i++) {
            cnt[i] = 0;
        }
    }
    void add(int x) {
        cnt[x] += 1;
        cnt[x] %= 2;
    }
    int encode() {
        int h = 0;
        for (int i = 0; i < 10; i++) {
            h = h * 3 + cnt[i];
        }
        return h;
    }
};
std::map<int,int> cnt;
std::string s;
void solve() {
    std::cin >> s;
    node nd;
    int ans = 0;
    cnt[0] = 1;
    for (auto c : s) {
        nd.add(c-'0');
        int k = nd.encode();
        ans += cnt[k];
        cnt[k] += 1;
    }
    std::cout << ans << "\n";
}

int main() {
    std::cin.tie(0)->sync_with_stdio(0);
    int t = 1;
    while (t--) solve();
    return 0;
}

posted on 2024-03-07 20:44  chenfy27  阅读(14)  评论(0)    收藏  举报