suffix_array(后缀数组)

#include
#include
#include
#include
using namespace std;

vector<int> grade;      
vector<int> sa;
vector<int> tempg;
int k;
string s;

bool cmpsa(int a, int b)
{
    if (grade[a] != grade[b])
        return grade[a] < grade[b];
    else
    {
        int nexa = a + k <= s.size() ? grade[a + k] : -1;
        int nexb = b + k <= s.size() ? grade[b + k] : -1;
        return nexa < nexb;
    }
}

void getsa()
{
    sa.clear();
    grade.clear();
    tempg.clear();
    for (int i = 0; i <= s.size(); i++)
    {
        sa.push_back(i);
        grade.push_back(i < s.size() ? s[i] : -1);
    }
    for (k = 1; k <= s.size(); k *= 2)
    {
        sort(sa.begin(), sa.end(),cmpsa);
        tempg = grade;
        tempg[sa[0]] = 0;
        for (int i = 1; i <= s.size(); i++)
        {
            tempg[sa[i]] = tempg[sa[i - 1]] + (cmpsa(sa[i - 1], sa[i]) ? 1 : 0);
        }
        grade = tempg;
    }
}

int main()
{
    while (cin >> s)
    {
        getsa();
        for (int i = 0; i < sa.size(); i++)
            cout << sa[i] << endl;
    }
    return 0;
}

你可能感兴趣的:(算法&数据结构)