Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- string s;
- void count_sort(vector<int> &p, vector<int> &c){
- int n = p.size();
- vector<int> cnt(n);
- for (auto x: c){
- cnt[x]++;
- }
- vector<int> p_new(n), pos(n);
- pos[0] = 0;
- for (int i=1; i<n; i++){
- pos[i] = pos[i-1] + cnt[i-1];
- }
- for (auto x: p){
- int i = c[x];
- p_new[pos[i]] = x;
- pos[i]++;
- }
- p = p_new;
- }
- vector<int> precalc(){
- int n = s.length();
- vector<int> p(n), c(n);
- // p stores the at present starting index of the smallest processed string
- // c stores the equivalence classes of the corresponding strings
- {
- // k = 0
- vector<pair<char, int> > a(n);
- for (int i=0; i<n; i++){
- a[i] = {s[i], i};
- }
- sort(a.begin(), a.end());
- for (int i=0; i<n; i++){
- p[i] = a[i].second;
- }
- c[p[0]] = 0;
- for (int i=1; i<n; i++){
- if (a[i].first == a[i-1].first){
- c[p[i]] = c[p[i-1]];
- }
- else c[p[i]] = c[p[i-1]] + 1;
- }
- }
- int k = 0;
- while((1<<k) < n){
- for (int i=0; i<n; i++){
- p[i] = (p[i] - (1<<k) + n)%n;
- }
- count_sort(p, c);
- vector<int> c_new(n);
- c_new[p[0]] = 0;
- for (int i=1; i<n; i++){
- pair<int, int> prev = {c[p[i-1]], c[(p[i-1] + (1<<k))%n]};
- pair<int, int> now = {c[p[i]], c[(p[i] + (1<<k))%n]};
- if (now == prev){
- c_new[p[i]] = c_new[p[i-1]];
- }
- else c_new[p[i]] = c_new[p[i-1]] + 1;
- }
- c = c_new;
- k++;
- }
- return p;
- }
- // int compare(string s, string &t){
- // // Check if t is a prefix of s
- // int m = t.size();
- // int n = s.size(); n--; //to remove the dollar from comparision
- // int i = 0;
- // while(i<m){
- // if (i>=n)return 1;
- // if (t[i] > s[i])return 1;
- // if (t[i]<s[i])return -1;
- // i++;
- // }
- // return 0;
- // }
- int search(vector<int> &p, string &t){
- int n = s.size(), m = t.size();
- int f = 0, l = n-1;
- while(f<=l){
- int mid = (f+l)/2;
- // int x = compare(s.substr(p[mid], n-p[mid]), t);
- string st = s.substr(p[mid], n-p[mid]-1);
- if (st.length() > t.length()){
- st = st.substr(0, t.length());
- }
- int x = t.compare(st);
- if(x == 0){
- return 1;
- }
- else if (x > 0){
- f = mid + 1;
- }
- else l = mid-1;
- }
- return 0;
- }
- int main()
- {
- // string s;
- cin>>s;
- s += '$';
- int n = s.size();
- vector<int> p = precalc();
- // for (int i=0; i<n; i++){
- // cout<<p[i]<<" ";
- // }
- int q; cin>>q;
- while(q--){
- string t;
- cin>>t;
- int x = search(p, t);
- if (x == 1)cout<<"Yes"<<endl;
- else cout<<"No"<<endl;
- }
- // vector<pair<pair<int, int>, int>> a;
- // for (int i=0; i<8; i++){
- // int l, r, k; cin>>l>>r>>k;
- // a.push_back({{l, r}, k});
- // }
- // radix_sort(a);
- // for (int i=0; i<8; i++){
- // cout<<a[i].first.first<<" "<<a[i].first.second<<" "<<a[i].second<<endl;
- // }
- }
Add Comment
Please, Sign In to add comment