1001: 字符串“水”题
时间限制: 1 Sec 内存限制: 128 MB提交: 271 解决: 96
[ 提交][ 状态][ 讨论版]
题目描述
给出一个长度为 n 的字符串(1<=n<=100000),求有多少个连续字串中所有的字母都出现了偶数次。
输入
第一行一个正整数 T,表示数据组数(1 <= T <= 10)。
接下来 T 行,每行有一个只包含小写字母的字符串。
接下来 T 行,每行有一个只包含小写字母的字符串。
输出
每个答案输出满足要求字符串个数。每个答案占一行。
样例输入
3
a
aabbcc
abcabc
样例输出
0
6
1
提示
来源
题意:给出一个长度为n的字符串(1<=n<=100000),求有多少个连续字串中所有的字母都出现了偶数次。
题解:
这道题完全是用了DP的思路的,就是用上次的奇偶个数加上本次的dp[][][][][]...[]+1,也就是每个字母的奇偶状态加1,但是这种写法太麻烦了,并且而且空间上也不允许,所以当时第一想法就是二进制压缩,然后map动态开辟查找,一发AC,看他们在卡题,我十几分钟1A还是比较爽的(我这是什么心理,队友不要看到)
状态压缩DP
#include <bits/stdc++.h>
using namespace std;
map<int,int>mmap;
char str[100010];
int main ()
{
int T;
scanf("%d",&T);
while(T--)
{
mmap.clear();
scanf("%s",str);
int len = strlen(str);
int state=0;
long long sum=0;
for(int i=0;i<len;i++){
state^=(1<<(str[i]-'a'));
if(state==0) sum++ ;
sum+=mmap[state];
mmap[state]++;
}
printf("%lld\n",sum);
}
return 0;
}
不过比赛之后这道题重判了,然后map+二进制压缩的方式竟然超时了,但是按照正常的时间复杂度是不会超的啊,无奈只好再哈希一发,不过这种用map哈希的方式还真是没用过,然后就过了,以后哈希就用这种哈希方式,因为是O(1)*每个map里面O(logm)查找,而m=2^26/MOD(本例中是100007),所以m约等于671,复杂度成了log(671),差不多也就是10,所以整体复杂度变成了10W*10=100w,然后*样例个数,1000W,时间复杂度很漂亮!!!
用map哈希,好屌的!!!
#include <bits/stdc++.h>
using namespace std;
#define MAX 100007
map<int,int>mmap[MAX+1];
char str[100010];
int main ()
{
int T;
scanf("%d",&T);
while(T--)
{
for(int i=0;i<MAX+1;i++)
mmap[i].clear();
scanf("%s",str);
int len = strlen(str);
int state=0;
long long sum=0;
for(int i=0;i<len;i++){
state^=(1<<(str[i]-'a'));
if(state==0) sum++;
sum+=mmap[state%MAX][state];
mmap[state%MAX][state]++;
}
printf("%lld\n",sum);
}
return 0;
}