Substring Score——The 11th Blue Bridge Cup AC
topic description
For a string S, we define the score f ( S ) of S as the number of characters in S that appear exactly once.
For example f("aba")=1, f("abc")=3
f("aaa")=0.
Now given a string S [ 0… n − 1 ], please calculate the non-empty substring S [ i . . j ] S[i…j]S[i…j] for all S, f ( S [ i . . j ] )
What is the sum of f(S[i…j])f(S[i…j]) .
Input format:
Enter a line containing a string S composed of lowercase letters.
Output Format
Output an integer representing the answer.
input sample
ababc
output sample
21
train of thought
- We require the sum of all non-empty substrings with one occurrence, that is, the sum of all strings that occur once based on each element of the string;
- Use pre[i] to record the position where the i-th letter appeared last time, then it can extend to the left up to pre[i] + 1, and there are i - pre[i] letters in total to the i-th letter;
- Use next[i] to record the position where the i-th letter appears next time, similarly, it can extend to the right up to next[i] - 1, and there are next[i] - i letters to the i-th letter;
- The multiplication of the two is the number of all substrings in which the letter appears once;
the code
#include <iostream>
// memset 需要 cstring 头文件
#include <cstring>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
int pre[N], nex[N];
int idx[26];
int main() {
string s;
cin >> s;
s = " " + s;
ll res = 0;
int n = s.size();
for (int i = 1; i < n; ++i) {
pre[i] = idx[s[i] - 'a'];
idx[s[i] - 'a'] = i;
}
for (int i = 0; i < 26; ++i)
idx[i] = n;
for (int i = n - 1; i; --i) {
nex[i] = idx[s[i] - 'a'];
idx[s[i] - 'a'] = i;
}
for (int i = 1; i < n; ++i) {
res += (ll) (i - pre[i]) * (nex[i] - i);
}
cout << res;
return 0;
}
The following topics are similar to this one and can be referred to. Everyone is welcome to criticize and correct
[Blue Bridge Cup 2020 Preliminary Competition] substring score and problem solution C++