fork(13) download
  1. import java.io.IOException;
  2. import java.util.Arrays;
  3. import java.util.Scanner;
  4.  
  5. public class Main {
  6.  
  7. public static void main(String[] args) throws IOException {
  8.  
  9. Scanner sc = new Scanner(System.in);
  10.  
  11. int n = sc.nextInt(), m = sc.nextInt();
  12.  
  13. int[] leftMost = new int[n], rightMost = new int[n];
  14. int maxFloor = -1;
  15. Arrays.fill(leftMost, m + 1);
  16. for(int i = n - 1; i >= 0; --i)
  17. {
  18. String s = sc.next();
  19. for(int j = 0; j < m + 2; ++j)
  20. if(s.charAt(j) == '1')
  21. {
  22. rightMost[i] = j;
  23. if(maxFloor == -1)
  24. maxFloor = i;
  25. }
  26.  
  27. for(int j = m + 1; j >= 0; --j)
  28. if(s.charAt(j) == '1')
  29. leftMost[i] = j;
  30. }
  31.  
  32. int ans = 10000000;
  33.  
  34. for(int stairs = 0; stairs < (1 << n - 1); ++stairs)
  35. {
  36. int cur = 0, room = 0, floor = 0;
  37. while(floor <= maxFloor)
  38. {
  39. if(room == 0)
  40. {
  41. cur += rightMost[floor] - room;
  42. room = rightMost[floor];
  43. }
  44. else
  45. {
  46. cur += room - leftMost[floor];
  47. room = leftMost[floor];
  48. }
  49.  
  50. if(floor == maxFloor)
  51. break;
  52. int nxtStairs = (stairs & (1 << floor)) == 0 ? 0 : m + 1;
  53. cur += Math.abs(nxtStairs - room) + 1;
  54.  
  55. room = nxtStairs;
  56. ++floor;
  57. }
  58. ans = Math.min(ans, cur);
  59. }
  60.  
  61. System.out.println(ans);
  62.  
  63. sc.close();
  64. }
  65. }
Runtime error #stdin #stdout #stderr 0.21s 2841600KB
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 Main.main(Main.java:11)