fork download
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class StringQueries {
  5. public static void main(String args[])throws Exception {
  6. Reader re = new Reader(System.in);
  7. int N = re.nextInt();
  8. int Q = re.nextInt();
  9. String S = re.next();
  10.  
  11. int pre[][] = new int[26][N+1];
  12. for(int i=0; i<26; i++){
  13. pre[i][0] = 0;
  14. for(int j=0; j<N; j++){
  15. pre[i][j+1] = pre[i][j];
  16. if(S.charAt(j)=='a'+i)
  17. pre[i][j+1]++;
  18. }
  19. }
  20.  
  21. while(Q-->0){
  22. int L = re.nextInt();
  23. int R = re.nextInt();
  24. int f[] = new int[26];
  25. for(int i=0; i<26; i++)
  26. f[i] = pre[i][R]-pre[i][L-1];
  27.  
  28. int m = (int)1e6;
  29. for(int i=0; i<26; i++){
  30. int d = 0, k = f[i];
  31. for(int j=0; j<26; j++){
  32. if(f[j]<f[i])
  33. d += f[j];
  34. else
  35. d += f[j]-k;
  36. }
  37. m = Math.min(m, d);
  38. }
  39.  
  40. System.out.println(m);
  41. }
  42. }
  43. }
  44.  
  45.  
  46. class Reader{
  47. String words[];
  48. int p;
  49. br = new BufferedReader(new InputStreamReader(in));
  50. words = new String[]{};
  51. p = 0;
  52. }
  53.  
  54. void ensureInput() throws Exception{
  55. while(p==words.length){
  56. words = br.readLine().split("\\s+");
  57. p = 0;
  58. }
  59. }
  60.  
  61. String next() throws Exception{
  62. ensureInput();
  63. return words[p++];
  64. }
  65.  
  66. int nextInt() throws Exception{
  67. return Integer.parseInt(next());
  68. }
  69. }
Success #stdin #stdout 0.04s 711168KB
stdin
8 2
abcdabcd
1 6
2 7
stdout
2
2