2872. 子串分值和 ###K //K
题目链接:https://www.acwing.com/problem/content/2875/
思路:对于每个字母 只有他在子串中第一个出现的时候才有贡献
所以考虑从1~n枚举 对于每个s[i] 计算出所有包含他的子串,且他是第一个出现的种类字母的子串数量即可
lst[i] 记录的是 i类字母上一次出现的位置, 假设 当前枚举到j 字母种类为a 那么 左端点可选情况为
j-lst[a] 右端点为n-j+1 所以两者相乘即是 该字母第一次出现的子串的数量
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=1e5+10; 4 const int mod=1e9+7; 5 #define ll long long 6 #define ull unsigned long long 7 #define pi pair<int,int> 8 #define fi first 9 #define sc second 10 #define pb push_back 11 12 char s[maxn]; 13 int lst[26]; 14 15 int main() 16 { 17 ios::sync_with_stdio(false); 18 cin.tie(0); 19 cin>>(s+1); 20 int n=strlen(s+1); 21 ll ans=0; 22 for(int i=1;i<=n;i++) 23 { 24 int x=s[i]-'a'; 25 int q=i-lst[x]; 26 int h=n-i+1; 27 ans+=1ll*q*h; 28 lst[x]=i; 29 } 30 cout<<ans<<'\n'; 31 32 33 34 }
考虑dp[i] 为以i为右端点的贡献和, 每次dp[i]=dp[i-1] + i-last[s[i]] 转移过来即可,
相当于每次只用当前的s[i] 去找前面的位置,找到第一个没重复的都是能算上贡献的
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define ll long long 4 #define pi pair<int,int> 5 #define pb push_back 6 #define fi first 7 #define sc second 8 #define ull unsigned long long 9 const int maxn=1e5+10; 10 const int mod=998244353; 11 12 13 int last[maxn]; 14 char s[maxn]; 15 int dp[maxn]; 16 17 18 int main() 19 { 20 ios::sync_with_stdio(0); 21 cin.tie(0); 22 cin>>s+1; 23 int n=strlen(s+1); 24 dp[1]=1; 25 last[s[1]-'a']=1; 26 ll ans=dp[1]; 27 for(int i=2;i<=n;i++) 28 { 29 int x=s[i]-'a'; 30 dp[i]=dp[i-1]+i-last[x]; 31 last[x]=i; 32 ans+=dp[i]; 33 } 34 cout<<ans<<'\n'; 35 36 37 }