Quantcast
Channel: CodeChef Discuss - latest questions
Viewing all articles
Browse latest Browse all 39796

KAN13C - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author: Dr. M Sohel Rahman
Tester:Jingbo Shang
Editorialist:Jingbo Shang

DIFFICULTY:

Medium

PREREQUISITES:

KMP

PROBLEM:

Given a string S[1..n], for each prefix of S[1..i], calculate largest pre[i], such that S[1..pre[i]] is same as S[i-pre[i]+1,i].

EXPLANATION:

This is a classical problem in Knuth–Morris–Pratt (KMP) algorithm. It is easy to see that pre[i]≤pre[i-1]+1, since S[1..pre[i]]=S[i-pre[i]+1..i] and S[1..pre[i-1]]=S[i-pre[i-1]..i-1]. Furthermore, we can “Jump” followed the pre[]. Therefore, we can get the main procedure as following:

    pre[1] = 0;  // by the definition of the problem
    for (int i = 2; i <= n; ++ i) {
        int k = pre[i - 1];
        while (k != 0 && s[k + 1] != s[i]) {
            k = pre[k];
        }
        if (s[k + 1] == s[i]) {
            pre[i] = k + 1;
        } else {
            pre[i] = 0; // all failed
        }
    }

See Wiki Pedia for more details:

http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.
Tester's solution can be found here.


Viewing all articles
Browse latest Browse all 39796

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>