Boring count (尺取法)

本文解析了一道计数子串中每种字母重复次数不超过K次的问题,采用尺取法进行高效求解,详细介绍了算法流程及注意事项,避免重复计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given a string S consisting of lowercase letters, and your task is counting the number of substring that the number of each lowercase letter in the substring is no more than K.

Input

In the first line there is an integer T , indicates the number of test cases.
For each case, the first line contains a string which only consist of lowercase letters. The second line contains an integer K.

[Technical Specification]
1<=T<= 100
1 <= the length of S <= 100000
1 <= K <= 100000

Output

For each case, output a line contains the answer.

Sample Input

3
abc
1
abcabc
1
abcabc
2

Sample Output

6
15
21

题意:输入字符串, 和一个k, 计数子串中有多少个子串的每种字母重复次数不超过k次。

题解:尺取法, 尺取终点为最后一个字母重复次数为k + 1时, 此时用公式n * (n + 1) / 2可直接计算出当前所得的到子串数量, 然后前推尺子的起点, 直到最后一个字母出现次数为k。不过要注意在后边用公式计数时会有重复计算。可以用一个变量记录上次尺子的终点, 用后来这次尺子的起点, 剪掉重复部分的子串总数即可。

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll vis[30] = {0};
int main()
{
    //printf("%lld\n",&a);
    ll i, j, n, t, k, m;
    long long ans;
    scanf("%lld", &t);
    while(t--){
        memset(vis,0,sizeof(vis));
        ans = 0;
        string a;
        char ch = 'z' + 2;
        cin >> a;
        a += ch;
        scanf("%lld", &k);
        ll s = 0, e = -1, ls = -1, le = -1;
        for(i = 0;i < a.length();i++){
            ll q = a[i] - 'a';
            vis[q]++;
            e++;
            //cout<<q<<" "<<s<<" "<<e<<" "<<le<<endl;
            if(vis[q] > k)
            {
                if(le < s)
                    ans += ((e - s) * (e - s + 1) / 2);
                else
                    ans += ((e - s) * (e - s + 1) / 2 - (le - s + 1) * (le - s + 2) / 2);
                le = e - 1;
                //cout<<ans<<endl;
                //cout<<"up:"<<le<<endl;
                while(1){
                    ll qq = a[s] - 'a';
                    vis[qq]--;
                    s++;
                    if(vis[qq] == k)
                        break;
                }
            }
            else if(i == a.length() - 1){
                if(le < s)
                    ans += ((e - s) * (e - s + 1) / 2);
                else
                    ans += ((e - s) * (e - s + 1) / 2 - (le - s + 1) * (le - s + 2) / 2);
                break;
            }
        }
        printf("%lld\n", ans);
    }
    return 0;
}

比赛时爆了int没有发现。太难受了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值