Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- #define endl "\n"
- using namespace std;
- using ll = long long;
- using ld = long double;
- using pii = pair<int, int>;
- constexpr int N = 1e5 + 1;
- constexpr int mod = 1e9 + 7;
- struct Node{
- bool isTerm;
- int link;
- int nextTerm;
- int par;
- int symb;
- vector<int> go;
- vector<int> next;
- Node(){
- next.resize(126 - 31);
- go.resize(126 - 31);
- nextTerm = 0;
- link = 0;
- par = 0;
- symb = 0;
- }
- };
- vector<Node> trie;
- int n;
- string query, text;
- vector<bool> ans;
- vector<bool> used;
- vector<int> temp;
- void build(){
- trie.emplace_back();
- }
- void add(string& s){
- int i = 0;
- for (auto c: s){
- if (trie[i].next[c - 32] == 0){
- trie[i].next[c - 32] = trie.size();
- trie.emplace_back();
- trie.back().par = i;
- trie.back().symb = c - 32;
- }
- i = trie[i].next[c - 32];
- }
- trie[i].isTerm = 1;
- }
- void init(){
- queue<int> q;
- trie[0].link = trie[0].par = 0;
- for (int i = 0; i < 126 - 31; i++){
- if (trie[0].next[i] == 0){
- trie[0].go[i] = 0;
- }
- else {
- trie[0].go[i] = trie[0].next[i];
- q.push(trie[0].next[i]);
- }
- }
- while(!q.empty()){
- int v = q.front();
- q.pop();
- trie[v].link = trie[v].par ? trie[trie[trie[v].par].link].go[trie[v].symb] : 0;
- trie[v].nextTerm = trie[trie[v].link].isTerm ? trie[v].link : trie[trie[v].link].nextTerm;
- for (int i = 0; i < 126 - 31; i++){
- if (trie[v].next[i]){
- trie[v].go[i] = trie[v].next[i];
- q.push(trie[v].next[i]);
- }
- else
- trie[v].go[i] = trie[trie[v].link].go[i];
- }
- }
- }
- bool work(string& t){
- int v = 0;
- bool ans = 0;
- for (auto c: t){
- v = trie[v].go[c - 32];
- if (!used[v]){
- for (int u = v; u && !used[u]; u = trie[u].nextTerm){
- if (trie[u].isTerm){
- ans = 1;
- break;
- }
- used[u] = 1;
- temp.push_back(u);
- }
- if (ans)
- break;
- }
- }
- while(temp.size()){
- used[temp.back()] = 0;
- temp.pop_back();
- }
- return ans;
- }
- void Solve() {
- build();
- cin >> n;
- getline(cin, query);
- for (int i = 0; i < n; i++){
- getline(cin, query);
- add(query);
- }
- init();
- used.resize(trie.size());
- while(getline(cin, text)){
- cout << (work(text) ? text : "") << endl;
- }
- }
- int main(){
- ios::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- Solve();
- return 0;
- }
Add Comment
Please, Sign In to add comment