#294 (div.2) D.A and B and Interesting Substring
来源:互联网 发布:网络与信息安全政府令 编辑:程序博客网 时间:2024/06/05 10:02
1.题目描述:点击打开链接
2.解题思路:本题要求在s中找满足下列条件的字串:(i)i+1~j-1的字符串权值之和为0;(ii)s[i]==s[j];处理带权字符串的一般解法是利用前缀和。但我最初的算法效率十分低下:先求出前i个字符的权和。并将26个字母出现的位置依次保存到vector中。随后从0~len依次枚举每个位置的字符s[i],并枚举它的下一个出现位置,再计算这段子串是否满足条件(1)。这种算法在第6组数据中就TLE了。无奈只能寻找新的解法。
由条件一可以推知sum[i]=sum[j-1],如果扫描到第j位时先不加上权值,那么就有sum[i]==sum[j]了。如果我们把sum值放入s[i]的map中来统计以s[i]结尾时sum的出现次数,那么自然也满足了条件(2)。因此新的算法就不难想出了:事先开一个26位长的map,保存以该字符结尾的子串遇到的所有sum值的次数。从头到尾扫描一遍s,先令所有的sum值出现次数为0,每次先累加以s[i]结尾且权值之和恰好是sum(sum暂时不累加s[i]处的权值)的子串的个数,即m[s[i]][sum],然后再更新s[i]处结尾的sum值,进而更新m[s[i]][sum]的值。详细细节见代码注释。
3.代码:
#define _CRT_SECURE_NO_WARNINGS #include<iostream>#include<algorithm>#include<string>#include<sstream>#include<set>#include<vector>#include<stack>#include<map>#include<queue>#include<deque>#include<cstdlib>#include<cstdio>#include<cstring>#include<cmath>#include<ctime>#include<functional>using namespace std;#define N 100000+10int word[26];char s[N];int main(){//freopen("test.txt", "r", stdin);long long cnt = 0,sum=0;for (int i = 0; i < 26; i++)scanf("%d", word + i);scanf("%s", s);int len = strlen(s);map<long long, long long>m[26];for (int i = 0; i < len; i++){int x = s[i] - 'a';//s[i]的序号cnt += m[x][sum];//先累加以s[i]结尾且权值之和恰好是sum的子串的个数sum += word[x];//更新sum值,累加上s[i]的权值m[x][sum]++;//更新sum值出现的次数}cout << cnt << endl;return 0;}
0 0
- #294 (div.2) D.A and B and Interesting Substring
- Codeforces Round #294 (Div. 2)D. A and B and Interesting Substrings
- hash(Codeforces Round #294 (Div. 2)D. A and B and Interesting Substrings)
- Codeforces Round #294 (Div. 2) -- D. A and B and Interesting Substrings
- Codeforces Round #294 (Div. 2) D. A and B and Interesting Substrings
- Codeforces Round #294 (Div. 2) D. A and B and Interesting Substrings(map)
- 【codeforces】Round #294 (Div. 2) D. A and B and Interesting Substrings
- Codeforces Round #294 (Div. 2) D. A and B and Interesting Substrings(前缀和+map)
- Codeforces Round #294 (Div. 2) D题:A and B and Interesting Substrings
- Codeforces Round #294 (Div. 2) D. A and B and Interesting Substrings
- Codeforces Round #294 (Div. 2)-D. A and B and Interesting Substrings
- CF(#294 div2):D. A and B and Interesting Substrings
- Codeforces 519D - A and B and Interesting Substrings (思维)
- Codeforces 519D A and B and Interesting Substrings
- A and B and Interesting Substrings - CodeForces 519 D dp
- Codefources 519D. A and B and Interesting Substrings
- CodeForces 519D A and B and Interesting Substrings
- coderforce 519D A and B and Interesting Substrings
- POJ1011 Sticks DFS+剪枝
- Linux Platform Device and Driver : platform_add_devices()->platform_driver_register()
- 杭电第1008题-----Elevator
- 云计算的三种服务模式
- jquery实现点击劫持代码
- #294 (div.2) D.A and B and Interesting Substring
- 【日常学习】【非指针链表】Uva11988 - Broken Keyboard (a.k.a. Beiju Text)题解
- c++ – 标准容器可以继承吗
- centos6.5下安装codeblocks过程记录
- HDU 5131 Song Jiang's rank list (14广州 排序 水题)
- Spark安装和使用
- 如何设定App的推广目标?
- LeetCode: Median of Two Sorted Arrays
- 师兄教你和面试官扯淡