結果
問題 | No.1095 Smallest Kadomatsu Subsequence |
ユーザー |
|
提出日時 | 2021-12-20 08:54:31 |
言語 | Go (1.23.4) |
結果 |
AC
|
実行時間 | 319 ms / 2,000 ms |
コード長 | 1,922 bytes |
コンパイル時間 | 14,896 ms |
コンパイル使用メモリ | 230,912 KB |
実行使用メモリ | 16,000 KB |
最終ジャッジ日時 | 2024-09-15 15:13:44 |
合計ジャッジ時間 | 19,864 ms |
ジャッジサーバーID (参考情報) |
judge6 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 30 |
ソースコード
package main import ( "fmt" "bufio" "os" "sort" "math" ) func Min(a, b int) int { if a < b { return a } else { return b } } type SegmentTree struct { n int tree []int } func newSegmentTree(n int) *SegmentTree{ sp := new(SegmentTree) sp.n = 1 for sp.n < n { sp.n *= 2 } sp.tree = make([]int, 2*sp.n) for i := 0; i < 2*sp.n; i++ { sp.tree[i] = math.MaxInt64 } return sp } func (this *SegmentTree) set(idx, x int) { idx += this.n this.tree[idx] = x for idx > 0 { idx >>= 1 this.tree[idx] = Min(this.tree[2 * idx], this.tree[2 * idx + 1]) } } func (this *SegmentTree) query(lt, rt int) int { lt += this.n rt += this.n vl, vr := math.MaxInt64, math.MaxInt64 for rt - lt > 0 { if lt & 1 != 0 { vl = Min(vl, this.tree[lt]) lt++ } if rt & 1 != 0 { rt-- vr = Min(this.tree[rt], vr) } lt >>= 1 rt >>= 1 } return Min(vl, vr) } func main() { r := bufio.NewReader(os.Stdin) w := bufio.NewWriter(os.Stdout) defer w.Flush() var N int fmt.Fscan(r, &N) A := make([][2]int, N) for i := 0; i < N; i++ { var x int fmt.Fscan(r, &x) A[i] = [2]int{x, i} } sort.Slice(A, func(i, j int) bool { if A[i][0] < A[j][0] { return true } else if A[i][0] > A[j][0] { return false } else { return A[i][1] < A[j][1] } }) res := math.MaxInt64 st1 := newSegmentTree(N) for i := 0; i < N; i++ { a, idx := A[i][0], A[i][1] st1.set(idx, a) lt := st1.query(0, idx) rt := st1.query(idx + 1, N) if lt == math.MaxInt64 || rt == math.MaxInt64 { continue } res = Min(res, lt + rt + a) } st2 := newSegmentTree(N) for i := N-1; i >= 0; i-- { a, idx := A[i][0], A[i][1] st2.set(idx, a) lt := st2.query(0, idx) rt := st2.query(idx + 1, N) if lt == math.MaxInt64 || rt == math.MaxInt64 { continue } res = Min(res, lt + rt + a) } if res == math.MaxInt64 { fmt.Fprintln(w, -1) } else { fmt.Fprintln(w, res) } }