bzoj 3439: Kpm的MC密码 Trie+动态开点线段树

题目大意:

http://www.lydsy.com/JudgeOnline/problem.php?id=3439

题解:

首先我们发现这道题要查的是后缀不是前缀.
如果查前缀就可以迅速查找到字符串了不是吗hhhhh.
所以我们把所有的串倒过来
然后在每个节点上维护一颗线段树储存以它为根的子树中结尾的字符串的编号支持查找k大即可.
他们说这会T,但我跑的挺快的.

#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
inline void read(int &x){
	x=0;char ch;bool flag = false;
	while(ch=getchar(),ch<'!');if(ch == '-') ch=getchar(),flag = true;
	while(x=10*x+ch-'0',ch=getchar(),ch>'!');if(flag) x=-x;
}
inline int cat_max(const int &a,const int &b){return a>b ? a:b;}
inline int cat_min(const int &a,const int &b){return a<b ? a:b;}
const int maxn = 320010;
struct Edge{
	int to,next;
}G[maxn<<1];
int head[maxn],cnt;
void add(int u,int v){
	G[++cnt].to = v;
	G[cnt].next = head[u];
	head[u] = cnt;
}
int ch[maxn][30],a[maxn],nodecnt;
char s[maxn];
void insert(int id){
	int n = strlen(s+1);
	int nw = 0;
	for(int i=n;i>=1;--i){
		if(ch[nw][s[i] - 'a'] == 0){
			ch[nw][s[i] - 'a'] = ++nodecnt;
			nw = nodecnt;
		}else nw = ch[nw][s[i] - 'a'];
	}add(nw,id);
}
int ind[maxn],oud[maxn],dfs_clock;
#define v G[i].to
void dfs(int u){
	int num = dfs_clock;
	for(int i = head[u];i;i=G[i].next){
		a[++dfs_clock] = v;
	}
	for(int i = 'a';i <= 'z';++i){
		if(ch[u][i-'a'] != 0){
			dfs(ch[u][i - 'a']);
		}
	}
	for(int i = head[u];i;i=G[i].next) ind[v] = num,oud[v] = dfs_clock;
}
#undef v
struct Node{
	Node *ch[2];
	int num;
	void update(){
		num = ch[0]->num + ch[1]->num;
	}
}*null,*T[maxn];
Node mem[maxn*30],*C;
inline void init(){
	C = mem;null = C++;
	null->ch[0] = null->ch[1] = null;
	null->num = 0;T[0] = null;
}
Node* build(Node *rt,int l,int r,int pos){
	Node *p = C++;*p = *rt;
	if(l == r){
		p->num ++ ;
		return p;
	}
	int mid = l+r >> 1;
	if(pos <= mid) p->ch[0] = build(rt->ch[0],l,mid,pos);
	else p->ch[1] = build(rt->ch[1],mid+1,r,pos);
	p->update();return p;
}
int query(Node *p1,Node *p2,int l,int r,int x){
	while(l != r){
		int mid = l+r >> 1;
		int tmp = p2->ch[0]->num - p1->ch[0]->num;
		if(x > tmp){
			x -= tmp;
			p1 = p1->ch[1];p2 = p2->ch[1];
			l = mid+1;
		}else{
			p1 = p1->ch[0];p2 = p2->ch[0];
			r = mid;
		}
	}return l;
}
int main(){
	int n;read(n);
	init();
	for(int i=1;i<=n;++i){
		scanf("%s",s+1);
		insert(i);
	}
	dfs(0);
	for(int i=1;i<=n;++i) T[i] = build(T[i-1],1,n,a[i]);
	for(int i=1,x;i<=n;++i){
		read(x);
		if(oud[i] - ind[i] < x) puts("-1");
		else printf("%d\n",query(T[ind[i]],T[oud[i]],1,n,x));
	}
	getchar();getchar();
	return 0;
}
posted @ 2017-02-28 21:19  Sky_miner  阅读(244)  评论(0编辑  收藏  举报