zoukankan      html  css  js  c++  java
  • Period :KMP

    I - Period

    Problem Description

    For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), 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 A K , that is A concatenated K times, for some string A. Of course, we also want to know the period K. 

    Input

    The input file 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. 

    Output

    For each test case, output “Test case #” and the consecutive test case number on a single line; then, for 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 Input

    3
    aaa
    12
    aabaabaabaab
    0

    Sample Output

    Test case #1
    2 2
    3 3

    Test case #2
    2 2
    6 2
    9 3
    12 4

    题意:输入n,输入n个字符,判断这个字符串中,任意前缀中是否有循环节,输出这个前缀长度和循环次数。(循环次数大于等于二的)

    题解:利用KMP算法里的next【】数组,再适合不过了。

    样例分析:3 aaa   aa:前两个字符,循环次数2,输出2 2

             aaa:前三个字符,循环次数3,输出3 3

    #include<iostream>
    #include<algorithm>
    #include<string>
    #include<string.h>
    using namespace std;
    const int maxn = 1e6 + 10;
    int nex[maxn];
    
    void getnext(string pat, int lenpat) {   
    	int i = 0;
    	int j = nex[0] = -1;                            //j相当于记录nex[i]的值
    	while(i<lenpat){								 //求next[1]~next[len-1]
    		if (j == -1 || pat[i] == pat[j]) {
    			i++;
    			j++;
    			nex[i] = j;                             
    		}
    		else j = nex[j];			//j回退,直到j回退到-1或pat[i]==pat[j+1]
    	}
    }
    
    int main() {
    	ios::sync_with_stdio(0);
    	int n, ans = 1;
    	string s;
    	while (cin >>n &&n) {
    		memset(nex, 0, sizeof(nex));
    		cin >> s;
    		cout << "Test case #" << ans << endl, ans++;
    		getnext(s, n);
    		for (int i =1; i <=n; i++) {
    			//cout << nex[i] << " ";
    			int t = i - nex[i];
    			if (i% t == 0 && i / t >1)
    				cout << i << " " << i / t << endl;
    		}
    		cout << endl;
    	}
    	return 0;
    }
    
  • 相关阅读:
    java获取文件夹下所有目录
    java下载zip文件
    oracle 递归查询数据
    easyUi刷新 tabs
    jsp引入本地图片
    zabbix web监测设置
    jenkins部署
    ss 异常活动端口查询-std
    logrotate 日志分割
    rsync删除大量小文件
  • 原文地址:https://www.cnblogs.com/52dxer/p/10498081.html
Copyright © 2011-2022 走看看