SP7258 SUBLEX

(color{#0066ff}{ 题目描述 })

给定一个字符串,求排名第k小的串

(color{#0066ff}{输入格式})

第一行给定主串(len<=90000)

第二行给定询问个数T<=500

随后给出T行T个询问,每次询问排名第k小的串,范围在int内

(color{#0066ff}{输出格式})

对于每一个询问,输出T行,每行为排名第k小的串

(color{#0066ff}{输入样例})

aaa
2
2
3

(color{#0066ff}{输出样例})

aa
aaa

(color{#0066ff}{数据范围与提示})

none

(color{#0066ff}{ 题解 })

求第k小,考虑在Sam上贪心

这时我们需要的siz是节点,所以统一dfs处理(注意记忆化)

然后依次贪心就行了

#include<bits/stdc++.h>
using namespace std;
#define LL long long
LL in() {
	char ch; int x = 0, f = 1;
	while(!isdigit(ch = getchar()))(ch == '-') && (f = -f);
	for(x = ch ^ 48; isdigit(ch = getchar()); x = (x << 1) + (x << 3) + (ch ^ 48));
	return x * f;
}
const int maxn = 2e5 + 5;
struct SAM {
protected:
	struct node {
		node *ch[26], *fa;
		int len, siz;
		node(int len = 0, int siz = 0): fa(NULL), len(len), siz(siz) {
			memset(ch, 0, sizeof ch);
		}
	};
	node *root, *tail, *lst;
	node pool[maxn];
	void extend(int c) {
		node *o = new(tail++) node(lst->len + 1), *v = lst;
		for(; v && !v->ch[c]; v = v->fa) v->ch[c] = o;
		if(!v) o->fa = root;
		else if(v->len + 1 == v->ch[c]->len) o->fa = v->ch[c];
		else {
			node *n = new(tail++) node(v->len + 1), *d = v->ch[c];
			std::copy(d->ch, d->ch + 26, n->ch);
			n->fa = d->fa, d->fa = o->fa = n;
			for(; v && v->ch[c] == d; v = v->fa) v->ch[c] = n;
		}
		lst = o;
	}
	void clr() {
		tail = pool;
		root = lst = new(tail++) node();
	}
	void getans(int k, node *o) {
		if(!k) return;
		for(int i = 0; i <= 25; i++) {
			if(o->ch[i]) {
				if(o->ch[i]->siz >= k) {
					putchar((char)(i + 'a'));
					getans(k - 1, o->ch[i]);
					return;
				}
				else k -= o->ch[i]->siz;
			}
		}
	}
	void getsiz(node *o) {
		if(o->siz) return;
		o->siz = 1;
		for(int i = 0; i <= 25; i++) if(o->ch[i]) getsiz(o->ch[i]), o->siz += o->ch[i]->siz;
	}
public:
	SAM() { clr(); }
	void ins(char *s) { for(char *p = s; *p; p++) extend(*p - 'a'); }
	void getsiz() { getsiz(root); }
	void getans(int k) { getans(k, root); }
}sam;
char s[maxn];
int main() {
	scanf("%s", s);
	sam.ins(s);
	sam.getsiz();
	for(int T = in(); T --> 0;) {
		int k = in();
		sam.getans(k);
		puts("");
	}
	return 0;
}
原文地址:https://www.cnblogs.com/olinr/p/10253440.html