Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Слава Україні, Героям слава
- #pragma GCC optimize("O3")
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 1e4 + 1, ALPHA_SIZE = 26;
- string v[N];
- int dp[N];
- namespace Aho {
- struct Node {
- int p, char_p, link = -1, str_idx = -1, nxt[ALPHA_SIZE];
- Node(int _p = -1, int _char_p = -1) : p(_p), char_p(_char_p) {
- fill(nxt, nxt + ALPHA_SIZE, -1);
- }
- };
- vector<Node> nodes;
- int cnt = 0;
- // change this if different alphabet
- inline void add(string& p, int id = -1) {
- int u = 0;
- if (id == -1) id = cnt++;
- for (char &ch : p) {
- int c = ch - 'a';
- if (nodes[u].nxt[c] == -1) {
- nodes[u].nxt[c] = (int)nodes.size();
- nodes.push_back(Node(u, c));
- }
- u = nodes[u].nxt[c];
- }
- nodes[u].str_idx = id;
- }
- inline void build() {
- queue<int> q;
- for (int i = 0; i < ALPHA_SIZE; i++) {
- if (nodes[0].nxt[i] != -1) q.push(nodes[0].nxt[i]);
- else nodes[0].nxt[i] = 0;
- }
- while (q.size()) {
- int u = q.front();
- q.pop();
- int j = nodes[nodes[u].p].link;
- if (j == -1) nodes[u].link = 0;
- else nodes[u].link = nodes[j].nxt[nodes[u].char_p];
- if(nodes[u].str_idx == -1) {
- nodes[u].str_idx = nodes[nodes[u].link].str_idx;
- }
- for (int i = 0; i < ALPHA_SIZE; i++) {
- if (nodes[u].nxt[i] != -1) {
- q.push(nodes[u].nxt[i]);
- } else {
- nodes[u].nxt[i] = nodes[nodes[u].link].nxt[i];
- }
- }
- }
- }
- inline void match(string& s, int k) {
- int u = 0;
- for (char &ch : s) {
- int c = ch - 'a';
- u = nodes[u].nxt[c];
- int x = nodes[u].str_idx;
- if(x != k and x != -1) {
- dp[k] = max(dp[k], dp[x] + 1);
- }
- x = nodes[nodes[u].link].str_idx;
- if(x != k and x != -1) {
- dp[k] = max(dp[k], dp[x] + 1);
- }
- }
- }
- }
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- Aho::nodes.reserve((int)1e6);
- int n;
- while(cin >> n) {
- if(!n) break;
- Aho::nodes.clear();
- Aho::cnt = 0;
- Aho::nodes.push_back(Aho::Node());
- for(int i = 0; i < n; i++) {
- dp[i] = 1;
- cin >> v[i];
- }
- sort(v, v + n, [](string &a, string &b) {
- return a.size() < b.size();
- });
- for(int i = 0; i < n; i++) {
- Aho::add(v[i]);
- }
- Aho::build();
- int ans = 1;
- for(int i = 1; i < n; i++) {
- Aho::match(v[i], i);
- ans = max(ans, dp[i]);
- }
- cout << ans << "\n";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement