結果
問題 | No.595 登山 |
ユーザー |
![]() |
提出日時 | 2017-11-10 23:17:30 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 974 ms / 1,500 ms |
コード長 | 1,821 bytes |
コンパイル時間 | 2,077 ms |
コンパイル使用メモリ | 77,456 KB |
実行使用メモリ | 77,120 KB |
最終ジャッジ日時 | 2024-11-24 15:15:47 |
合計ジャッジ時間 | 20,262 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 4 |
other | AC * 25 |
ソースコード
import java.util.*;class Main {static final long I=1L<<50;public static void main(String[] args) {Scanner scan = new Scanner(System.in);int n=Integer.parseInt(scan.next());long p=Integer.parseInt(scan.next());long[] h=new long[n];for(int i=0;i<n;++i)h[i]=Integer.parseInt(scan.next());long[] l=new long[n],r=new long[n];l[0]=r[n-1]=0;for(int i=1;i<n;++i)l[i]=l[i-1]+Math.max(h[i]-h[i-1],0);for(int i=n-2;i>=0;--i)r[i]=r[i+1]+Math.max(h[i]-h[i+1],0);MaxSegmentTree s1=new MaxSegmentTree();MaxSegmentTree s2=new MaxSegmentTree();long[] dp=new long[n];dp[0]=0;dp[1]=0;s1.update(0,l[1]);s2.update(0,-r[1]);for(int i=1;i<n;++i){long m=l[i];m=Math.min(m,-s1.query(0,i)+l[i]+p);m=Math.min(m,-s2.query(0,i)-r[i]+p);dp[i]=m;if(i<n-1){s1.update(i,-m+l[i+1]);s2.update(i,-m-r[i+1]);}}System.out.println(dp[n-1]);}}class MaxSegmentTree {static final int SIZE = 1 << 18;static final long INFINITY = (1L << 61) - 1;long[] seg;MaxSegmentTree() {this.seg = new long[2 * SIZE];}void update(int x, long value) {x += SIZE - 1;this.seg[x] = value;while (x > 0) {x = (x - 1) / 2;this.seg[x] = Math.max(this.seg[2 * x + 1], this.seg[2 * x + 2]);}}long query(int l, int r) {l += SIZE - 1;r += SIZE - 1;long y = -INFINITY;while (l < r) {if ((l & 1) == 0) {y = Math.max(y, this.seg[l]);}if ((r & 1) == 0) {y = Math.max(y, this.seg[r - 1]);}l /= 2;r = (r - 1) / 2;}return y;}}