SAM求字典序前k大

  • 在后缀链接树上贪心即可 有点细节
#include 
using namespace  std;
//#define  int long long
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector<int> vi;
#define fi first
#define se second
#define pb  push_back
#define inf 1ll<<62
#define endl "\n"
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define de_bug(x) cerr << #x << "=" << x << endl
#define all(a) a.begin(),a.end()
#define IOS   std::ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define  fer(i,a,b)  for(int i=a;i<=b;i++)
#define  der(i,a,b)  for(int i=a;i>=b;i--)
const int mod = 1e9 + 7;
const int N = 2e6 + 10;
int n, m , k;
struct node {
	int len, fa;
	int son[26];
} tr[N];
ll f[N], ans;
vi g[N];
string s;
int cnt = 1;
int last = 1;
void extend (int c,int i) {
	int p = last, np = last = ++cnt;
	f[cnt] = i;
	tr[np].len = tr[p].len + 1;
	for(; p && !tr[p].son[c];  p = tr[p].fa) tr[p].son[c] = np;
	if(!p) tr[np].fa = 1;
	else {
		int q = tr[p].son[c];
		if(tr[q].len == tr[p].len + 1)tr[np].fa = q;
		else {
			int nq = ++cnt;
			tr[nq] = tr[q];
			tr[nq].len = tr[p].len + 1;
			tr[q].fa = tr[np].fa = nq;
			for(; p && tr[p].son[c] == q; p = tr[p].fa) tr[p].son[c] = nq;
		}
	}
}
void dfs(int u) {
	for(auto v : g[u]) {
		dfs(v);
		f[u]=max(f[u],f[v]);
	}
}
int dfn;
int sum[N];
int fan[N];

void dfs1(int u,int fa) {
	if(u!=1) {
		dfn++;
		sum[dfn]=sum[dfn-1]+tr[u].len-tr[tr[u].fa].len;
		fan[dfn]=u;
	}
	vector<array<int,2>>su;
	for(auto v:g[u]) {
		su.push_back({s[f[v]-tr[u].len],v});
	}
	sort(all(su));
	for(auto v:su) {
		dfs1(v[1],u);
	}
}
void solve() {
	cin >> s;
	n = s.size();
	reverse(all(s));
	s=" "+s;
	fer(i,1,n) {
		extend(s[i]-'a',i);
	}
	fer(i,1,cnt) {
		g[tr[i].fa].push_back(i);
	}
	dfs(1);
	dfs1(1,-1);
	cin>>m;
	int l=0,r=0;
//	de_bug(dfn);

	while(m--) {
		cin>>k;
		k=(k^l^r)+1;
		if(k<=sum[dfn]) {
			int t=lower_bound(sum+1,sum+dfn+1,k)-sum;
			int u=fan[t];
			int len=tr[u].len-(sum[t]-k);
			l=n-f[u]+1;
			r=l+len-1;
		} else {
			l=0,r=0;
		}
		cout<<l<<" "<<r<<endl;
	}


}
int  main() {
	IOS;
	int _ = 1;
	//cin>>_;
	while( _-- )
		solve();
}



你可能感兴趣的:(深度优先,算法,图论)