Cod sursa(job #2627014)

Utilizator lucametehauDart Monkey lucametehau Data 9 iunie 2020 12:51:28
Problema Substr Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.86 kb
#include <fstream>
#include <algorithm>
#include <cstring>

using namespace std;

ifstream cin ("seti.in");
ofstream cout ("seti.out");

struct S {
  int a, b, ind;
  bool operator < (const S &other) const {
    return (a < other.a || (a == other.a && b < other.b));
  }
} v[131075];

int n, m, k, l;

char s[131075], a[65];
int poz[2][131075], ind[131075];

int comp(int ind) {
  for(int i = 1; i <= k; i++) {
    if(s[ind + i - 1] < a[i])
      return -1;
    if(s[ind + i - 1] > a[i])
      return 1;
  }
  return 0;
}

int main() {
  cin >> n;
  for(int i = 1; i <= n; i++) {
    cin >> (a + 1);
    for(int j = 1; j <= 64; j++)
      s[(i - 1) * 64 + j] = a[j];
  }
  n *= 64;
  for(int i = 1; i <= n; i++)
    poz[0][i] = s[i] - 'a';
  l = 1;
  for(int i = 1; (1 << (i - 1)) <= n; i++, l = 1 - l) {
    for(int j = 1; j <= n; j++) {
      v[j].a = poz[1 - l][j];
      v[j].b = (j + (1 << (i - 1)) <= n ? poz[1 - l][j + (1 << (i - 1))] : 0);
      v[j].ind = j;
    }
    sort(v + 1, v + n + 1);
    for(int j = 1; j <= n; j++) {
      if(j > 1 && v[j].a == v[j - 1].a && v[j].b == v[j - 1].b)
        poz[l][v[j].ind] = poz[l][v[j - 1].ind];
      else
        poz[l][v[j].ind] = j;
    }
  }
  for(int i = 1; i <= n; i++)
    ind[poz[l][i]] = i;
  cin >> m;
  for(; m; m--) {
    cin >> (a + 1);
    k = strlen(a + 1);
    int st = 1, dr = n, mid, ans;
    while(st <= dr) {
      mid = (st + dr) >> 1;
      if(comp(ind[mid]) == -1)
        st = mid + 1;
      else
        dr = mid - 1;
    }
    ans = -st;
    if(comp(ind[st]) || st > n) {
      cout << "0\n";
      continue;
    }
    st = 1, dr = n;
    while(st <= dr) {
      mid = (st + dr) >> 1;
      if(comp(ind[mid]) <= 0)
        st = mid + 1;
      else
        dr = mid - 1;
    }
    ans += dr + 1;
    cout << ans << "\n";
  }
  return 0;
}