【前缀和】2021年度训练联盟热身训练赛第三场 K.Summer Trip

Summer Trip

题目大意

给定一个字符串,可以选择一个子数组,满足头尾均是这个子数组里唯一出现的字母。求合法的子数组个数。

解题思路

首先处理好每个字母出现个数的前缀和数组 s u m sum sum 和出现位置的数组 p o s pos pos。遍历字符串,每次求以当前字母为首个的合法子数组个数。

具体方法为,可以知道当前字母的位置 i i i 和当前字母下一次出现的位置 j j j,则求区间 [ i , j − 1 ] [i,j-1] [i,j1] 内的字母有几种,即为合法子数组个数~

需要注意的是,如果当前字母是最后一个,那么下一次出现的位置不是 0 0 0,而是看作数组末尾,不然会漏解~

参考代码

#include<stdio.h>
#include<iostream>
#include<vector>
#include<cstring>
#include<cstdio>
#include<climits>
#include<cmath>
#include<algorithm>
#include<queue>
#include<deque>
#include<map>
#include<unordered_map>
#include<set>
#include<stack>
//#define LOCAL  //提交时一定注释
#define VI vector<int>
#define eps 1e-8
#define io ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
using namespace std;
typedef long long LL;
typedef double db;
const int inf = 0x3f3f3f3f;
const LL INF = 1e18;
const int N = 1e5 + 10;
#define ls rt << 1
#define rs rt << 1 | 1
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1

inline int readint() {int x; scanf("%d", &x); return x;}


LL gcd(LL a, LL b) {
    return b == 0 ? a : gcd(b, a % b);
}

int sum[26][N], pos[26][N], cnt[26], now[26];  //cnt数组统计字母出现的次数,now标记当前某个字母进行到第几次

int cal(int id, int l, int r) {
    int ans = 0;
//    cout << "l:" << l << " r:" << r;
    for(int i = 0; i < 26; i++) {
//        cout << " i:" << i << " sum[r]:" << sum[i][r] << " sum[l:" << sum[i][l - 1] << endl;
        if (i == id && (sum[i][r] - sum[i][l - 1])) return 0;
        ans += (sum[i][r] - sum[i][l - 1]) ? 1 : 0;
    }
    return ans >= 1 ? ans : 0;
}

int main() {
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
//   freopen("output.txt", "w", stdout);
#endif
    string s; cin >> s;
    int len = s.length();
    s = ' ' + s;
    fill(cnt, cnt + 26, 1);
    fill(now, now + 26, 1);

    for(int i = 1; i <= len; ++i) {
        int id = s[i] - 'a';
        for(int k = 0; k < 26; k++) {
            sum[k][i] = (k == id ? (sum[k][i - 1] + 1) : sum[k][i - 1]);
        }
        pos[id][cnt[id]] = i;
        cnt[id]++;
    }
    LL ans = 0;
    for(int i = 1; i <= len; ++i) {
        int id = s[i] - 'a';
        int post = now[id] + 1;  //下一次出现的位置
        if (post <= cnt[id]) {  //相等也可以
            int l = pos[id][now[id]] + 1;
            int r;
            if (post == cnt[id]) r = len;
            else r = pos[id][post] - 1;
            if (l <= r) {
                ans += 1LL * cal(id, l, r);
//                cout << "post l:" << l << " post r:" << r;
            }
        }
//        cout << "id:" << id << " pre:" << pre << ' ' << "post:" << post << " ";
//        cout << "ans:" << ans << endl;
        now[id]++;
    }
    cout << ans;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值