Created
September 16, 2013 17:04
-
-
Save phonism/6583476 to your computer and use it in GitHub Desktop.
Codeforces 249 E. Tree-String Problem
http://codeforces.com/problemset/problem/291/E
dfs+kmp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cstring> | |
#include <algorithm> | |
#include <iostream> | |
#include <vector> | |
#include <string> | |
using namespace std; | |
const int maxn = 100100; | |
struct Edge { | |
int to; | |
string s; | |
Edge() {} | |
Edge(int too, string str) { | |
to = too; s = str; | |
} | |
}; | |
int n, ans = 0, next[maxn]; | |
string t; | |
vector<Edge> edge[maxn]; | |
void dfs(int u, int k) { | |
for (int l = 0; l < edge[u].size(); l++) { | |
int v = edge[u][l].to; | |
string str = edge[u][l].s; | |
int tmp = k, len = edge[u][l].s.size(); | |
for (int i = 0, j = k; i < len; i++) { | |
while (j != -1 && str[i] != t[j+1]) | |
j = next[j]; | |
if (str[i] == t[j+1]) j++; | |
if (j + 1 == t.size()) { | |
j = next[j]; ans++; | |
} | |
tmp = j; | |
} | |
dfs(v, tmp); | |
} | |
} | |
void work() { | |
cin >> n; | |
for (int i = 2; i <= n; i++) { | |
int p; | |
string str; | |
cin >> p >> str; | |
edge[p].push_back(Edge(i, str)); | |
} | |
cin >> t; | |
next[0] = -1; | |
for (int i = 1, j = -1; i < t.size(); i++) { | |
while (j != -1 && t[j+1] != t[i]) | |
j = next[j]; | |
if (t[j+1] == t[i]) { | |
next[i] = j + 1; j++; | |
} else { | |
next[i] = -1; | |
} | |
} | |
dfs(1, -1); | |
cout << ans << endl; | |
} | |
int main() { | |
work(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment