|
洛谷P2414
- #include <cstdio>
- #include <vector>
- #include <queue>
- using namespace std;
- const int maxn = 100010;
- const int maxc = 30;
- struct BIT {
- int n, t[maxn];
- void update(int k, int x) {
- for (int i = k; i <= n; i += i & (-i)) {
- t[i] += x;
- }
- }
- int query(int x) {
- int ans = 0;
- for (int i = x; i >= 1; i -= i & (-i)) {
- ans += t[i];
- }
- return ans;
- }
- } bt;
- struct ACTrie {
- int ch[maxn][maxc], cch[maxn][maxc], fa[maxn], tot = 1;
- int insert(char s[]) {
- int p = 1;
- for (int i = 0; s[i]; i++) {
- if (!ch[p][s[i] - 'a']) {
- ch[p][s[i] - 'a'] = ++tot;
- }
- p = ch[p][s[i] - 'a'];
- }
- return p;
- }
- int fail[maxn];
- vector<int> failson[maxn];
- int id[maxn], dfn[maxn], dfe[maxn], times = 0;
- queue<int> q;
- void init() {
- fail[1] = 1;
- for (int i = 0; i < 26; i++) {
- if (ch[1][i]) {
- q.push(ch[1][i]);
- fail[ch[1][i]] = 1;
- failson[1].push_back(ch[1][i]);
- } else {
- ch[1][i] = 1;
- }
- }
- while (!q.empty()) {
- int t = q.front();
- q.pop();
- for (int i = 0; i < 26; i++) {
- if (ch[t][i]) {
- q.push(ch[t][i]);
- fail[ch[t][i]] = ch[fail[t]][i];
- failson[ch[fail[t]][i]].push_back(ch[t][i]);
- } else {
- ch[t][i] = ch[fail[t]][i];
- }
- }
- }
- }
- void dfsfail(int u) {
- id[++times] = u;
- dfn[u] = times;
- for (int v : failson[u]) {
- if (v != u)
- dfsfail(v);
- }
- dfe[u] = times;
- }
- void buildac() {
- init();
- dfsfail(1);
- }
- } act;
- int n, k, x, y;
- int ed[100010];
- vector<int> id[100010];
- char s[100010], c;
- int ans[100010];
- vector<pair<int, int> > queries[100010];
- void dfs(int u) {
- bt.update(act.dfn[u], 1);
- for (int v : id[u]) {
- for (auto l : queries[v]) {
- ans[l.second] = bt.query(act.dfe[ed[l.first]]) - bt.query(act.dfn[ed[l.first]] - 1);
- }
- }
- for (int i = 0; i < 26; i++) {
- if (act.cch[u][i]) {
- dfs(act.cch[u][i]);
- }
- }
- bt.update(act.dfn[u], -1);
- }
- int main() {
- scanf("%s", s);
- int p = 1;
- for (int i = 0; s[i]; i++) {
- if (s[i] == 'B') {
- p = act.fa[p];
- } else if (s[i] == 'P') {
- ed[++k] = p;
- id[p].push_back(k);
- } else {
- if (!act.ch[p][s[i] - 'a']) {
- act.ch[p][s[i] - 'a'] = ++act.tot;
- act.cch[p][s[i] - 'a'] = act.tot;
- act.fa[act.ch[p][s[i] - 'a']] = p;
- }
- p = act.ch[p][s[i] - 'a'];
- }
- }
- act.buildac();
- bt.n = act.tot;
- scanf("%d", &n);
- for (int i = 1; i <= n; i++) {
- scanf("%d%d", &x, &y);
- queries[y].push_back({x, i});
- }
- dfs(1);
- for (int i = 1; i <= n; i++) {
- printf("%d\n", ans[i]);
- }
- return 0;
- }
复制代码
|
|