phanindhar1

Untitled

Jan 18th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.81 KB | None | 0 0
  1. package com.demo;
  2.  
  3. import java.util.*;
  4.  
  5. public class SnowSpread {
  6.     public static void main(String args[]) {
  7.         int[] input = {0, 1, 3, 0, 1, 2, 0, 4, 2, 0, 3, 2, 1};
  8.         System.out.println(solve(input));
  9.     }
  10.  
  11.     private static int solve(int[] input) {
  12.         PriorityQueue<AbstractMap.SimpleEntry<Integer, Integer>> heap = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
  13.         AbstractMap.SimpleEntry<Integer, Integer> val;
  14.         boolean[] visited = new boolean[input.length];
  15.         int sum = 0, index, curleft = 0, curright = 0;
  16.         for (int i = 0; i < input.length; i++) {
  17.             heap.add(new AbstractMap.SimpleEntry<Integer, Integer>(i, input[i]));
  18.         }
  19.         int va11 = heap.poll().getKey();
  20.         int va12 = heap.poll().getKey();
  21.         int left = Math.min(va11, va12);
  22.         int right = Math.max(va11, va12);
  23.         int height = Math.min(input[left], input[right]);
  24.         visited[left] = true;
  25.         visited[right] = true;
  26.         for (int i = left + 1; i < right; visited[i] = true, i++)
  27.             sum += height - input[i];
  28.  
  29.         while ((val = heap.poll()) != null) {
  30.             index = val.getKey();
  31.             if (!visited[index]) {
  32.                 if (index > right) {
  33.                     curleft = right;
  34.                     curright = index;
  35.                     right = index;
  36.                 } else if (index < left) {
  37.                     curleft = index;
  38.                     curright = left;
  39.                     left = index;
  40.                 }
  41.                 visited[index] = true;
  42.                 height = Math.min(input[curleft], input[curright]);
  43.                 for (int i = curleft + 1; i < curright; visited[i] = true, i++)
  44.                     sum += height - input[i];
  45.             }
  46.         }
  47.         return sum;
  48.     }
  49. }
Add Comment
Please, Sign In to add comment