Manioc

suf_trie

Mar 2nd, 2018
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define rep(i, a, b) for (int i = (a), i##_end = (b); i < i##_end; ++i)
  3. #define per(i, a, b) for (int i = (a), i##_end = (b); i >= i##_end; --i)
  4. using namespace std;
  5.  
  6. typedef unsigned uint;
  7.  
  8. const int N = 9e4, SIGMA = 26;
  9.  
  10. struct Node {
  11.     Node* word[SIGMA], *link;
  12.     int len;
  13.     uint sum[SIGMA];
  14. } node[2*N], * root = node;
  15.  
  16. int sz = 1;
  17. void add(int c){
  18.     static Node* last = root;
  19.     Node* now = node + sz++, * p = last;
  20.     last = now;
  21.  
  22.     now->len = p->len + 1;
  23.     for(;p && !p->word[c]; p = p->link) p->word[c] = now;
  24.  
  25.     if (!p) {
  26.         now->link = root;
  27.         return;
  28.     }
  29.     Node* q = p->word[c];
  30.     if (q->len == p->len + 1) {
  31.         now->link = q;
  32.     } else {
  33.         Node* clone = node + sz++;
  34.         *clone = *q;
  35.         clone->len = p->len + 1;
  36.         for(;p && p->word[c] == q; p = p->link) p->word[c] = clone;
  37.         now->link = q->link = clone;
  38.     }
  39. }
  40. bool vis[2*N];
  41. uint dfs(Node* no){
  42.     bool& v = vis[no-node];
  43.     if (v) return no->sum[SIGMA-1];
  44.     v = true;
  45.    
  46.     uint s = 1;
  47.     rep (i, 0, SIGMA) {
  48.         Node* v = no->word[i];
  49.         if (v) s += dfs(v);
  50.         no->sum[i] = s;
  51.     }
  52.     return s;
  53. }
  54. void query(uint k){
  55.     Node* x = root;
  56.     ++k;
  57.     while (k > 1) {
  58.         int c = 0;
  59.         while (x->sum[c] < k) ++c;
  60.         putchar('a' + c);
  61.         k -= c ? x->sum[c-1] : 1;
  62.         x = x->word[c];
  63.     }
  64.     putchar('\n');
  65. }
  66.  
  67. char s[N+1];
  68. int main(){
  69.     scanf("%s", s);
  70.     int n = 0;
  71.     while (s[n]) add(s[n++] - 'a');
  72.     dfs(root);
  73.     int q;
  74.     scanf("%d", &q);
  75.     while (q--) {
  76.         uint k;
  77.         scanf("%u", &k);
  78.         query(k);
  79.     }
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment