fork download
  1. #include<bits/stdc++.h>
  2. #define fr(i,a,b) for(int i=a;i<b;i++)
  3. #define mp make_pair
  4. #define pb push_back
  5. #define F first
  6. #define S second
  7. #define f(i,n) for(int i=0;i<n;i++)
  8. #define ll long long
  9.  
  10. using namespace std;
  11.  
  12. ll power(ll x,ll y, ll mod){
  13. ll res = 1LL;
  14. while(y>0){
  15. if(y&1)
  16. res = (res*x)%mod;
  17. y = y/2;
  18. res = (res*power(x,y,mod))%mod;
  19. }
  20. return res;
  21. }
  22.  
  23. void test(){
  24. int n;
  25. cin>>n;
  26. string s,pat;
  27. cin>>pat>>s;
  28. int p = 31;
  29. ll m1 = 1e9 + 7;
  30. ll m2 = 1e9 + 9;
  31. ll hash[s.length()+1];
  32. ll hash2[s.length()+1];
  33. hash[0] = 0;
  34. hash2[0] = 0;
  35. f(i,s.length()){
  36. hash[i+1] = (hash[i] + (s[i]-'a')*power(p,i,m1))%m1;
  37. hash2[i+1] = (hash2[i] + (s[i]-'a')*power(p,i,m2))%m2;
  38. }
  39. ll hashv = 0,hashv2 = 0;
  40. f(i,n){
  41. hashv = (hashv + (pat[i]-'a')*power(p,i,m1))%m1;
  42. hashv2 = (hashv2 + (pat[i]-'a')*power(p,i,m2))%m2;
  43. }
  44.  
  45. vector<int> ans;
  46. for(int i=0;i+n-1<s.length();i++){
  47. ll cur = (hash[i+n]-hash[i]+m1)%m1;
  48. ll comp = (hashv*power(p,i,m1))%m1;
  49. ll cur2 = (hash2[i+n]-hash2[i]+m2)%m2;
  50. ll comp2 = (hashv2*power(p,i,m2))%m2;
  51. if(cur==comp and cur2==comp2){
  52. ans.pb(i);
  53. }
  54. }
  55. f(i,ans.size())cout<<ans[i]<<"\n";
  56. if(ans.size()==0)cout<<"\n";
  57. }
  58.  
  59. int main(){
  60. int t=1;
  61. cin>>t;
  62. while(t--){
  63. test();
  64. }
  65. }
Success #stdin #stdout 0s 4396KB
stdin
3
2
na
banananobano
6
foobar
foo
9
foobarfoo
barfoobarfoobarfoobarfoobarfoo
stdout
2
4

3
9
15
21