Problem 46: Suffix Array Construction
Problem Statement: Given a string, construct its suffix array by sorting all of its suffixes and output the starting indices in sorted order (0-indexed).
Input
A single line containing the string.
Output
Print the starting indices of the suffixes in sorted order, separated by spaces.
Examples
Input:
banana
Output:
5 3 1 0 4 2
Solution Explanation
Method 1: Generate all suffixes, sort them using a standard sorting algorithm, and then output the starting indices. Method 2: Implement more efficient suffix array construction algorithms such as the doubling method or SA-IS algorithm, which have better performance on large strings.
Solution in C++
#include
#include
#include
#include
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s; cin >> s;
int n = s.size();
vector sa(n);
for (int i = 0; i < n; i++) sa[i] = i;
sort(sa.begin(), sa.end(), [&s](int i, int j){
return s.substr(i) < s.substr(j);
});
for (int i = 0; i < n; i++)
cout << sa[i] << (i < n-1 ? " " : "
");
return 0;
}