[Blue Bridge Cup 2020 Preliminary Competition] Substring Score and Solution C++

[Blue Bridge Cup 2020 Preliminary Competition] Substring Score and C++

Solution 1 - traversal + hash table

Only 60% of the samples can be passed, and most of the students use this method, so I won’t go into details

#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
    
    

  string s;
  cin >> s;
  int n = s.size();
  int res = n;
  for (int i = 0; i < n; ++i) {
    
    
    unordered_map<char, int> m;
      ++m[s[i]];
    for (int j = i + 1; j < n; ++j) {
    
    
      ++m[s[j]];
      res += m.size();
    }
  }
  cout << res;
  return 0;
}

AC plan

Some people say that this is called the multiplication principle, but I am more inclined to reverse thinking.

train of thought

  • The general idea is the sum of the number of elements in each substring. We might as well regard the element that appears for the first time as a repeated element as the active element.
  • Then the substring score sum isThe sum of the number of substrings that each element contributes to
  • The substring can be extended to the left to the place where it appeared last time (no occurrence is regarded as 0), and it can be extended to the end of the string to the right.
  • Then the number of active substrings for each element is the product of the number of possible cases for the left endpoint and the number of possible cases for the right endpoint.

the code

#include <iostream>
using namespace std;
int last[26];
int main() {
    
    
    string s;
    cin >> s;
    s = " " + s;
    long long res = 0;
    int n = s.size();
    for (int i = 1; i < n; ++i) {
    
    
        res +=(long long) (n - i) * (i - last[s[i] - 'a']);
        last[s[i] - 'a'] = i;
    }
    cout << res;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_64632836/article/details/128929645