POJ1261: Period

Source: Internet
Author: User

DescriptionFor each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, intrusive), we want to know whether the prefix is a periodic string. that is, for each I (2 <= I <= N) we want to know the largest K> 1 (if there is one) such that the prefix of S with length I can be written as AK, that is A concatenated K times, for some string. of course, we Also want to know the period K. inputThe input consists of several test cases. each test case consists of two lines. the first one contains N (2 <= N <= 1 000 000)-the size of the string S. the second line contains the string S. the input file ends with a line, having the number zero on it. outputFor each test case, output "Test case #" and the consecutive test case number on a single line; then, f Or each prefix with length I that has a period K> 1, output the prefix size I and the period K separated by a single space; the prefix sizes must be in increasing order. print a blank line after each test case. sample Input3aaa12aabaabaabaab0Sample OutputTest case #12 23 3 Test case #22 26 29 312 4 [cpp] # include <string. h> # include <iostream> # include <stdio. h> char str [1000005]; int next [1000005 ]; Void getnext () {int I = 0, j =-1; memset (next, 0, sizeof (next); next [0] =-1; while (str [I]) {if (j =-1 | str [I] = str [j]) {I ++; j ++; next [I] = j;} else j = next [j];} void kmp () {int I, t; for (I = 2; str [I-1]; I ++) {t = I-next [I]; if (I % t = 0 & I/t> 1) printf ("% d \ n", I, I/t) ;}} int main () {int n, cnt = 1; while (scanf ("% d", & n )! = EOF & n) {scanf ("% s", str); printf ("Test case # % d \ n", cnt ++); getnext (); kmp (); putchar (10);} return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.