fork download
  1. import java.io.*;
  2. import java.math.BigInteger;
  3. import java.util.*;
  4.  
  5. class CyclicHashes implements Runnable {
  6.  
  7. private BufferedReader in;
  8. private PrintWriter out;
  9.  
  10. void init() throws FileNotFoundException {
  11. out = new PrintWriter(System.out);
  12. }
  13.  
  14. public static void main(String[] args) {
  15. new Thread(null, new CyclicHashes(), "", 1l * 200 * 1024 * 1024).start();
  16. }
  17.  
  18. public void run() {
  19. try {
  20. init();
  21. solve();
  22. out.close();
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. System.exit(-1);
  26. }
  27. }
  28.  
  29. int n;
  30. int prime1;
  31. int mod1;
  32. int[] pow1;
  33. int[] h1;
  34.  
  35. void init(char[] s) {
  36. Random rnd = new Random();
  37. prime1 = BigInteger.valueOf(3000 + rnd.nextInt(500))
  38. .nextProbablePrime().intValue();
  39. mod1 = BigInteger.valueOf((int) 1e9 + rnd.nextInt(500))
  40. .nextProbablePrime().intValue();
  41. n = s.length;
  42. pow1 = new int[n];
  43. pow1[0] = 1;
  44. for (int i = 1; i < n; i++) {
  45. pow1[i] = (int) ((long) pow1[i - 1] * prime1 % mod1);
  46. }
  47. h1 = new int[n];
  48. h1[0] = s[0];
  49. for (int i = 1; i < n; i++) {
  50. h1[i] = (int) ((h1[i - 1] + (long) pow1[i] * s[i]) % mod1);
  51. }
  52. }
  53.  
  54. int getHash(int L, int R, int[] h, int[] pow, int mod) {
  55. int hash = h[R];
  56. if (L > 0)
  57. hash -= h[L - 1];
  58. if (hash < 0)
  59. hash += mod;
  60. return (int) ((long) hash * pow[n - R - 1] % mod);
  61. }
  62.  
  63. boolean equals(int L1, int R1, int L2, int R2) {
  64. long hash1 = getHash(L1, R1, h1, pow1, mod1);
  65. long hash2 = getHash(L2, R2, h1, pow1, mod1);
  66. return hash1 == hash2;
  67. }
  68.  
  69. void solve() throws IOException {
  70. int n = Integer.parseInt(in.readLine());
  71. String s = in.readLine();
  72. String t = in.readLine();
  73. StringBuilder sb = new StringBuilder();
  74. sb.append(s);
  75. sb.append(t);
  76. sb.append(t);
  77. char[] res = sb.toString().toCharArray();
  78.  
  79. init(res);
  80.  
  81. for (int shift = 0; shift < n; shift++) {
  82. if (equals(0, n - 1, n + shift, 2 * n - 1 + shift)) {
  83. out.println(shift);
  84. return;
  85. }
  86. }
  87. out.println(-1);
  88.  
  89. }
  90.  
  91. }
Success #stdin #stdout 0.05s 320704KB
stdin
11
abracadabra
racadabraab
stdout
9