字符串“水”题(状压)

题意:给出一个长度为n的字符串(1<=n<=100000),求有多少个连续字串中所有的字母都出现了偶数次。

分析:

1、从左到右扫一遍字符串,利用状态压缩记录下截止到当前位置各字母是奇数还是偶数,若奇数,则为1,否则为0。

2、试想,如果扫一个字符串时,截止到某种状态所有个数为奇数的字母与截止到之前某种状态所有个数为奇数的字母完全相同,则这两个状态之间的子串所有的字母一定都是出现了偶数次。(奇-奇=偶)

而,因为奇数用1表示,且所有个数为奇数的字母相同,(eg:00010000000100000001000001与00010000000100000001000001),那么这两个状态压缩之后一定相同。

3、如果扫到的状态之前出现过,则ans+=该状态之前出现过的状态数。

eg:ababab,

扫到第一个字母a时,状态为1(00000000000000000000000001),当扫到第5个字母a时,状态又为1,则两状态之间的字母一定都是出现了偶数次。

4、对于状态为0的情况,即截止到当前状态,所有字母都出现了偶数次,则其与最初始(尚未开始扫字符串)的状态相同,可与最初始的状态构成符合要求的连续子串,所以status[0]=1。

eg:abababab,

扫到第四个字母,状态为0,ans+=status[0],然后ans=1。截止到第四个字母的子串与截止到第0个字母的子串形成的连续子串,即abab,所有的字母都出现了偶数次。++status[0](状态为0的状态数又多了一个,应加1)。

扫到第八个字母,状态为0,ans+=status[0],然后ans=3。截止到第八个字母的子串分别与   截止到第0个字母的子串和截止到第四个字母的子串   形成的连续子串,即abab,所有的字母都出现了偶数次。

5、PS:status开数组的话大约6000多万,清空会超时,因此改用map。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define lowbit(x) (x & (-x))
const double eps = 1e-8;
inline int dcmp(double a, double b){
    if(fabs(a - b) < eps) return 0;
    return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, -1, 0, 1, 0, -1, -1, 1, 1};
const int dc[] = {0, 0, 1, 0, -1, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = (1 << 26) + 10;
const int MAXT = 100000 + 10;
using namespace std;
map<int, int> status;
char s[MAXT];
int main(){
    int T;
    scanf("%d", &T);
    while(T--){
        status.clear();
        status[0] = 1;
        int now = 0;
        scanf("%s", s);
        int len = strlen(s);
        LL ans = 0;
        for(int i = 0; i < len; ++i){
            now ^= (1 << (s[i] - 'a'));
            ans += LL(status[now]);
            ++status[now];
        }
        printf("%lld\n", ans);
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/tyty-Somnuspoppy/p/6765664.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值