跳到正文

个人记录

题解P11965 [GESP202503 七级] 等价消除

lyz0427约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月15日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

题目大意

说白了就是让你求出字符串 SS 的连续的子串中有多少个各字母个数是偶数个的子串的个数。

思路分析

  1. 这里先来讲一下暴力。
  • 首先前缀和求出各字母个数,然后 O(n2×26)O(n^2×26) 获得 2020 分,代码如下。
C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+5;
int a[N][26];
signed main(){
	int n;
	cin>>n;
	string s;
	cin>>s;
	s=" "+s;
	for(int i=1;i<=n;i++){
		for(int j=0;j<26;j++){
			a[i][j]=a[i-1][j];
		}
		a[i][s[i]-'a']++;
	}
    int ans=0;
	for(int i=1;i<=n;i++){
		for(int j=1;j<i;j++){
			bool f=0;
			for(int k=0;k<26;k++){
				int t=a[i][k]-a[j-1][k];
				if(t%2==1){
					f=1;
					break;
				}
			}
			if(!f) ans++;
		}
	}
	cout<<ans<<endl;
	return 0;
}
  1. 正解。
  • 由于我们是用 a[N][26] 存储的,所以费时间费空间,我们把这个数组全取模后全为 0,10,1 不可能有别的了。
  • 由同余定理可知: 如果a取模2=b取模2,(a−b)取模2=0如果a取模2=b取模2,(a-b)取模2=0 ,所以我们把每一个字母的值看成 2^(s[i]-'a')的话, a[N][26] 就能降一维变成 a[N]。
  • 因为只有两数相等时才能相减等于 00 ,所以我们可以创建一个 map<int,vector<int>> mp; ,然后用高斯求和求出答案。
  • 但是如果自己也能是一个答案,还要加上自己。

代码

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
map<int,vector<int>> mp;
signed main(){
	int n;
	cin>>n;
	string s;
	cin>>s;
	s=" "+s;
	int t=0;
	for(int i=1;i<=n;i++){
		t^=(1<<(s[i]-'a'));
		mp[t].push_back(i);
	}
	int ans=0;
	for(auto i:mp){
		int len=i.second.size();
		ans+=(len-1)*len/2;
		if(i.first==0) ans+=len;
	}
	cout<<ans<<endl;
	return 0;
}
原文