Problem description
Goddess invited acdream to have a gala. Obviously, as ACM's leader, there are no fewer balloons ~. Goddess has prepared three colors of balloons, red, yellow, green (Traffic lights ?)
A balloon cannot satisfy the goddess. The goddess must write on the balloon.
What should I do ~? The ghost of string Shenma loves ~
Goddess first took out a string, and then wrote every real prefix of the string to the yellow balloon, and every real suffix to the green balloon, every real substring is written on a red balloon.
For a string s [1... n], the prefix of true · is s [1... i] (1 <= I <n) ·, true · suffix is s [j... n] (1 <j <= N), true · substring is s [I... j] (1 <I <= j <n)
So the goddess got a lot of balloons ~
So what is the longest string that appears on three colors of balloons at the same time?
Shima, 404 Not found? Can't such a string be found? Goddess is angry! Then we have to output "angry goddess. (Double quotation marks are not included. Note the case sensitivity and there is a space in the middle)
Input Multiple groups of data, each group of data is a string of up to 100000 characters in length, output for each group of data, output a string sample input
abcabcabcaaaaaaaaaabcabc
Sample output
Abcaaaaaangry goddess
Solution:
In fact, this question is to find whether there are three identical substrings in a string. The three strings must be S1 [0 .. I <n-1], S2 [0 <I .... j <n-1], S3 [0 <j .... n-1], the first practice is to directly use the KMP algorithm to search and match
Condition, but because the data times out, I finally think of the principle of the next array. Its value is the number of equal prefixes and suffixes, as long as we find out the same as next [I] in the middle, it will meet the condition. Of course, this is also the largest string. First, we will set Len = next
[Strlen (AB)], locate from the end, find the matching result, and output the result. If the result is not found, Len = next [Len]. Otherwise, it will time out! If no one is found, the end condition is Len =-1 or = 0.
AC code:
#include <iostream>#include <algorithm>#include <stdio.h>#include <string.h>#include <stdlib.h>using namespace std;char ab[100005];char nb[100005];int next[100005];void getNext(char *nb){ int j=0,k=-1; next[0]=-1; while(j<strlen(nb)) { if(k==-1||nb[j]==nb[k]) { j++; k++; next[j]=k; } else k=next[k]; }}int main(){ int i,temp,max1; while(gets(ab)) { temp=0;max1=0; strcpy(nb,ab); getNext(nb); int len=next[strlen(ab)]; while(len!=0&&len!=-1) { for(i=2;i<strlen(ab)-1;i++) { if(len==next[i]) { temp=1;break; } } if(temp) break; len=next[len]; } if(!temp) printf("angry goddess"); for(i=0;i<len;i++) { printf("%c",ab[i]); } cout<<endl; } return 0;}
[Acdream] goddess teaches you strings-three balloons