> File Name: 5790.cpp > Author: jiangyuzhu > Mail: 834138558@qq.com > Created Time: 2016/10/6 19:03:47 ************************************************************************/ #include<iostream> #include<cstdio> #include<cstring> #include<queue> #include<vector> #include<set> #include<map> #include<algorithm> using namespace std; typedef unsigned long long ull; const int maxn = 1e5 + 5, maxm = 50 * maxn; int lson[maxm], rson[maxm], t[maxn], tree[maxm]; int tot; int build(int l, int r) { int root = tot++; tree[root] = 0; int mid = l + r >> 1; if(l == r) return root; lson[root] = build(l, mid); rson[root] = build(mid + 1, r); return root; } int update(int root, int l, int r, int num, int val) { int newroot = tot++; tree[newroot] = tree[root] + val; if(l == r) return newroot; int mid = l + r >> 1; if(num <= mid){ lson[newroot] = update(lson[root], l, mid, num, val); rson[newroot] = rson[root]; }else{ rson[newroot] = update(rson[root], mid + 1, r, num, val); lson[newroot] = lson[root]; } return newroot; } int query(int L, int R, int l, int r, int i) { if(l == L && r == R) return tree[i]; int mid = l + r >> 1; if(R <= mid) return query(L, R, l, mid, lson[i]); else if(L > mid) return query(L, R, mid + 1, r, rson[i]); else return query(L, mid, l, mid, lson[i]) + query(mid + 1, R, mid + 1, r, rson[i]); } char s[maxn]; int last[maxn]; int son[maxn][26]; int n; int root, alloc; int newnode() { memset(son[alloc], -1, sizeof(son[alloc])); return alloc++; } void init() { alloc = 0; root = newnode(); } void insert(int id) { int len; int p = root; t[id] = t[id - 1]; for(int i = 0; s[i]; ++i){ int nx = s[i]-'a'; int &node = son[p][nx]; if(node == -1) node = newnode(); if(last[node] != -1) t[id] = update(t[id], 1, n, last[node], -1); t[id] = update(t[id], 1, n, id, 1); last[node] = id; p = son[p][nx]; } } int main (void) { while(~scanf("%d", &n)){ tot = 0; init(); memset(last, -1, sizeof(last)); t[0] = build(1, n); for(int i = 1; i <= n; ++i){ scanf("%s", s); insert(i); } int q;scanf("%d", &q); int l, r; int z = 0; while(q--){ scanf("%d%d", &l, &r); l = (z + l) % n + 1; r = (z + r) % n + 1; if(l > r) swap(l, r); z = query(l, r, 1, n, t[r]); printf("%d\n", z); } } return 0; }
|