SPOJ:String Play (?)
String Play
Milo has a string S of length L. Tutu picks a random prefix and Mota picks a random suffix ofS.
Now, Chotku is given a task of concatenating the two strings that Tutu and Mota have chosen, in respective order. Chotku wonders, how many distinct prefix-suffix concatenation is possible out there of string S.
So you know what to do.. Help Chotku!
Input
Input file contains several lines of text. Each line contains a string, S. End of file marks the end of input.
Output
Output one integer per string, denoting the number of distinct prefix-suffix concatenation of the string.
Constraints
-
Strings consist of lower-case letters only.
-
1 ≤ L ≤ 10000006
Sample Input |
Output for Sample Input |
abc |
8 |
Explanation:
For sample #1, the 3 prefixes are “a”, “ab”, “abc”
The 3 suffixes are “c”, “bc”, “abc”
And the 8 distinct concatenations are, “ac”, “abc”, “aabc”, “abbc”, “ababc”, “abcc”, “abcbc”, “abcabc”.
题意:一个字符串,A取一段前缀,B取一段后缀,然后连接起来组成一个新的字符串S,问可以组成多少种新的字符串,重复的只统计一次。
思路:首先必须是O(n)的复杂度,然后我什么都不知道了。
#include<bits/stdc++.h> const int maxn=10000010; using namespace std; char c[maxn]; int num[27]; int main() { int Len,i; long long ans; while(~scanf("%s",c+1)){ Len=strlen(c+1); ans=Len; memset(num,0,sizeof(num)); for(i=1;i<=Len;i++) num[c[i]-'a']++; for(i=Len-1;i>=1;i--){ ans+=Len-num[c[i+1]-'a']; if(c[i+1]==c[Len]) ans++; } printf("%lld\n",ans); } return 0; }