fork download
  1. //Coded by Vishal Mourya
  2. //If you use this code anywhere you need to mention my name as above
  3.  
  4. /* package codechef; // don't place package name! */
  5.  
  6. import java.util.*;
  7. import java.lang.*;
  8. import java.io.*;
  9.  
  10. /* Name of the class has to be "Main" only if the class is public. */
  11. //Note : If you are running this code on codechef then replace Ideone with Codechef
  12. class Ideone //Codechef
  13. {
  14. public static void main (String[] args) throws java.lang.Exception
  15. {
  16. try{
  17. //write your code here
  18. Scanner sc = new Scanner(System.in);
  19. int t = sc.nextInt();
  20. while(t > 0)
  21. {
  22. int p,sum=0,min_sum=0,max_sum=0;
  23. String str;
  24.  
  25. int count=0,count1=0;
  26. int n = sc.nextInt();
  27. p = sc.nextInt();
  28. sc.nextLine();
  29.  
  30. str = sc.nextLine();
  31.  
  32. char charArray[] = str.toCharArray();
  33. Arrays.sort(charArray);
  34. String str1 = new String(charArray);
  35.  
  36.  
  37. for(int i=0;count1<n && i<str1.length();++i)
  38. {
  39. int curr = str1.charAt(i);
  40. if( curr % p != 0)
  41. {
  42. int curr1 = str1.charAt(i);
  43. min_sum += curr1;
  44. count1++;
  45. }
  46.  
  47.  
  48. }
  49.  
  50. for(int j=str1.length()-1; count<n && j>=0 ;j--)
  51. {
  52. int curr = str1.charAt(j);
  53. if( curr % p != 0 )
  54. {
  55. int curr1 = str1.charAt(j);
  56. max_sum += curr1;
  57. count++;
  58. }
  59.  
  60. }
  61.  
  62.  
  63. if ((max_sum==0 && min_sum==0 && p!= 1 ) || (count1 <n || count <n) || (n>str1.length() || p==1))
  64. {
  65. System.out.println("-1");
  66. }
  67. else
  68. System.out.println(min_sum + " " + max_sum );
  69. }//end of test case loop
  70. }//end of try block
  71. catch(Exception e){
  72. //Exception here
  73. }
  74. }//end of main
  75.  
  76. }//end of class Codechef
Success #stdin #stdout 0.13s 37732KB
stdin
2
2 2 
alex
5 2
john
stdout
198 198
-1