fork download
  1. import java.util.Scanner;
  2.  
  3. class SamosaBhai {
  4. public static void main(String[] args){
  5. int n =0;
  6. Scanner keyboard = new Scanner(System.in);
  7. Scanner input = new Scanner(System.in);
  8. System.out.println("Enter number of test Cases:");
  9. n = keyboard.nextInt();
  10. int[] ans = new int[n];
  11. for(int i = 0; i< n ;i++){
  12.  
  13. //no. of houses and power 'd' is stored here
  14. String get = input.nextLine();
  15. String[] numarray = get.split(" "); // splitting string by spaces
  16. int num = Integer.parseInt(numarray[0]); // number of houses
  17. int d = Integer.parseInt(numarray[1]); // power to be raised
  18.  
  19.  
  20. // positions of the houses is stored here
  21. String entry = input.nextLine();
  22. Scanner scanner = new Scanner(entry);
  23. int[] pos = new int[num];
  24. for (int j= 0;j<num;j++) {
  25. pos[j] = scanner.nextInt();
  26. }
  27. scanner.close();
  28.  
  29. ans[i] = postalCharge(pos, d, n);
  30.  
  31. }
  32. keyboard.close();
  33. input.close();
  34. for(int p =0; p<n; p++)
  35. System.out.println(ans[p]);
  36.  
  37. }
  38.  
  39. // function to calculate the postal charges between all the houses
  40. public static int postalCharge(int[] location, int d, int n){
  41. int total =0;
  42. for (int i = 0; i<n; i++){
  43. for(int j =0; j< n; j++){
  44. int n1 = location[i];
  45. int n2 = location[j];
  46. total += Math.pow(Math.abs(n1-n2),d);
  47. }
  48. }
  49. return total;
  50. }
  51. }
Runtime error #stdin #stdout #stderr 0.16s 321344KB
stdin
5
2 2
7 2
2 3
7 2
3 2
1 3 2
10 2
1 2 3 4 5 6 7 8 9 10
10 10
1 2 3 4 5 6 7 8 9 10
stdout
Enter number of test Cases:
stderr
Exception in thread "main" java.util.NoSuchElementException: No line found
	at java.util.Scanner.nextLine(Scanner.java:1540)
	at SamosaBhai.main(Main.java:14)