Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class MapRoute {
  4. public static void main(String[] arguments) {
  5. Scanner in=new Scanner(System.in);
  6. int n=in.nextInt();
  7. int[] is=new int[n*n], d=new int[n*n];
  8. PQ pq=new PQ(n);
  9. V v;
  10. for (int i=0; i < n*n; i+=1) {
  11. is[i]=in.nextInt();d[i]=Integer.MAX_VALUE;
  12. }
  13. d[0]=is[0];
  14. for (int i=0; i < n*n; i+=1) pq.ins(new V(i, d[i]));
  15. while (pq.l!=0) {
  16. v= pq.ext();
  17. if (v.i>n-1 && d[v.i-n]>d[v.i]+is[v.i-n]) {
  18. d[v.i-n]=d[v.i]+is[v.i-n];pq.rm(new V(v.i-n, d[v.i-n]));
  19. }
  20. if (v.i<n*n-n && d[v.i+n]>d[v.i]+is[v.i+n]) {
  21. d[v.i+n]=d[v.i]+is[v.i+n];pq.rm(new V(v.i+n, d[v.i+n]));
  22. }
  23. if (v.i%n!=0 && d[v.i-1]>d[v.i]+is[v.i-1]) {
  24. d[v.i-1]=d[v.i]+is[v.i-1];pq.rm(new V(v.i-1, d[v.i-1]));
  25. }
  26. if (v.i%n!=n-1 && d[v.i+1]>d[v.i]+is[v.i+1]) {
  27. d[v.i+1]= d[v.i]+is[v.i+1];pq.rm(new V(v.i+1, d[v.i+1]));
  28. }
  29. }
  30. System.out.println(d[n*n-1]);
  31. }
  32. }
  33.  
  34. class V {
  35. public int d, i;
  36. V(int i, int d) {this.i=i; this.d=d;}
  37. public boolean cmp(V v) {return d-v.d>0;}
  38. }
  39.  
  40. class PQ {
  41. public int l;
  42. public V[] vs;
  43. public int[] h;
  44. public PQ(int n) {
  45. l = 0;vs = new V[n*n+2*n+1]; h = new int[n*n+2*n+1];
  46. }
  47. public void ins(V x) {
  48. l++;
  49. while (l>1 && vs[l>>1].cmp(x)) {
  50. vs[l]=vs[l>>1];h[vs[l].i] = l;l=l>>1;
  51. }
  52. vs[l] = x;h[vs[l].i] = l;
  53. }
  54. public void rm(V x) {
  55. while (h[x.i]-1>0 && vs[h[x.i]>>1].cmp(x)) {
  56. vs[h[x.i]]=vs[h[x.i]>>1];h[vs[h[x.i]].i] = h[x.i];h[x.i]=h[x.i]>>1;
  57. }
  58. vs[h[x.i]] = x;h[vs[h[x.i]].i] = h[x.i];
  59. }
  60. public V ext() {
  61. V x = vs[1];l--;int i = 1, c;
  62. if (2>l)c = 0;
  63. else if (2==l || vs[3].cmp(vs[2]))c = 2;
  64. else c = 3;
  65. while(c > 0 && vs[l + 1].cmp(vs[c])) {
  66. vs[i] = vs[c];h[vs[i].i] = i;i = c;
  67. if ((i<<1)-l>0)c = 0;
  68. else if ((i<<1)-l==0 || vs[(i<<1)+1].cmp(vs[i<<1]))c = i<<1;
  69. else c=(i<<1)+1;
  70. }
  71. vs[i] = vs[l+1];h[vs[i].i] = i;return x;
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement