fork download
  1. import java.math.*;
  2. import java.util.*;
  3.  
  4. class BigNumbers
  5. {
  6. public static void main(String args[])
  7. {
  8. Scanner sc=new Scanner(System.in);
  9.  
  10. int n, A;
  11. String str;
  12. char[] s;
  13. int[] pi, cnt;
  14. BigInteger[] a, b;
  15. int[][] classes;
  16.  
  17. A=sc.nextInt();
  18. str = sc.nextLine();
  19. str = sc.nextLine();
  20.  
  21. n=str.length();
  22.  
  23. classes=new int[A+1][];
  24. cnt=new int[A+1];
  25. for(int i=1;i<=A;i++) cnt[i]=0;
  26.  
  27. pi=new int[n];
  28. s=new char[n];
  29.  
  30. for(int i=0;i<n;i++)
  31. {
  32. s[i]=str.charAt(i);
  33. cnt[(int)s[i]-(int)'a'+1]++;
  34. if(i==0) pi[0]=0;
  35. else
  36. {
  37. int j = pi[i-1];
  38. while(j > 0 && s[i] != s[j]) j = pi[j-1];
  39. if (s[i] == s[j]) j++;
  40. pi[i] = j;
  41. }
  42. }
  43.  
  44. for(int i=1;i<=A;i++)
  45. {
  46. if(cnt[i]>0) classes[i]=new int[cnt[i]];
  47. cnt[i]=0;
  48. }
  49.  
  50.  
  51. for(int i=0;i<n;i++)
  52. {
  53. int cl=(int)s[i]-(int)'a'+1;
  54. classes[cl][cnt[cl]]=i+1;
  55. cnt[cl]++;
  56. }
  57.  
  58. a=new BigInteger[n+1];
  59. b=new BigInteger[n+1];
  60.  
  61. a[0]=BigInteger.ONE;
  62. b[0]=BigInteger.ZERO;
  63.  
  64.  
  65. for(int i=0; i<n; i++)
  66. {
  67. a[i+1]=a[i].multiply(BigInteger.valueOf(A));
  68. b[i+1]=b[i].multiply(BigInteger.valueOf(A)).subtract(BigInteger.valueOf(A));
  69. for(int k=1;k<=A;k++)
  70. {
  71. char x=(char)(k-1 + 'a');
  72. if(x==s[i]) continue;
  73. int j=0, L, R, m;
  74. if(classes[k]!=null)
  75. {
  76. L=0;
  77. R=cnt[k]-1;
  78. while(R-L>1)
  79. {
  80. m=(L+R)/2;
  81. if(classes[k][m]<=pi[i]+1) L=m;
  82. else R=m;
  83. }
  84. if(classes[k][L]<=pi[i]+1) j=classes[k][L];
  85. if(classes[k][R]<=pi[i]+1) j=classes[k][R];
  86. }
  87. a[i+1]=a[i+1].subtract(a[j]);
  88. b[i+1]=b[i+1].subtract(b[j]);
  89. }
  90. }
  91.  
  92. ans=BigInteger.valueOf(-1).multiply(b[n]).divide(a[n]);
  93. System.out.println(ans.toString());
  94. }
  95. }
Runtime error #stdin #stdout #stderr 0.12s 29444KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Exception in thread "main" java.util.NoSuchElementException
	at java.util.Scanner.throwFor(Scanner.java:862)
	at java.util.Scanner.next(Scanner.java:1485)
	at java.util.Scanner.nextInt(Scanner.java:2117)
	at java.util.Scanner.nextInt(Scanner.java:2076)
	at BigNumbers.main(Main.java:18)