C++プログラミング10.12 Theme section(kmpアルゴリズム)

5099 ワード

Problem Description
It's time for music! A lot of popular musicians are invited to join us in the music festival. Each of them will play one of their representative songs. To make the programs more interesting and challenging, the hosts are going to add some constraints to the rhythm of the songs, i.e., each song is required to have a 'theme section'. The theme section shall be played at the beginning, the middle, and the end of each song. More specifically, given a theme section E, the song will be in the format of 'EAEBE', where section A and section B could have arbitrary number of notes. Note that there are 26 types of notes, denoted by lower case letters 'a' - 'z'.
To get well prepared for the festival, the hosts want to know the maximum possible length of the theme section of each song. Can you help us?
 
Input
The integer N in the first line denotes the total number of songs in the festival. Each of the following N lines consists of one string, indicating the notes of the i-th (1 <= i <= N) song. The length of the string will not exceed 10^6.
 
Output
There will be N lines in the output, where the i-th line denotes the maximum possible length of the theme section of the i-th song.
 
頭の上に同じもの、尾の上に同じもの、真ん中に同じものがあります.英語を読むのは本当に疲れます.の
でも少しは勉強になりました==
 
shall beの使い方.先日kmpについて話したばかりです.の授業ではあまり聞き取れなかったので,自分で書いてしまった.お祝いをする.
 
#include<iostream>
#include<stdio.h>
#include<cstring>

#define NUM 1000000
using namespace std;

struct song
{
    char word[NUM];
    int length;
};

int main()
{
    int N;
    cin>>N;
    song *p =new song[N];
    for(int i=0; i<N; i++)
        //    gets(p[i].word);           = =              = =
    {
		cin>>p[i].word;
		if(getchar()=='
') { int l=0; for(int j=0;p[i].word[j]!='\0';j++) l++; p[i].length = l;// } } //cout<<p[0].length<<endl;// length //cout<<p[1].length<<endl;// length //cout<<p[2].length<<endl;// length //cout<<p[3].length<<endl;// length //cout<<p[4].length<<endl;// length //cout<<endl; for(int j=0; j<N; j++)// song { int max = 0; int num = 0; bool cyclength = true; for(int i=1; i<=p[j].length/3; i++)// E { bool current = true; //if(!cyclength)// , 。 bababa , 。 // break; for(int s=0; s<i; s++)// { if(p[j].word[s]!=p[j].word[p[j].length-i+s]) { current = false; // cyclength = false; break; } } if(current)// { num = i; int *str = new int[i]; str[0] = 0; for(int q=0; q<i; q++)//next { for(int w=0; w<q; w++) { bool count = true; if(w+q>=i) break; if(p[j].word[w]==p[j].word[w+q]) { str[q] = w; count = false; } else { if(count) str[q]=0; break; } } } current = false; int c=i; int m=0; while(c<p[j].length-i)//kmp { bool changec = false; if(p[j].word[m]==p[j].word[c]) { m++; changec= true; } else m = str[m]; if(m==i) { current = true; break; } if(m==0||changec) c++; } } if(current)// { if(max>num) continue; else max = num; } } cout<<max<<endl; } delete p; return 0; }