P3558 [POI2013]BAJ-Bytecomputer

[POI2013]BAJ-Bytecomputer

思路:

动态规划,f[i][j],表示前i个第i个是以j结尾得最少操作次数

代码:

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

var n int

const N = 2000010

var a [N]int64
var f [N][3]int64 //0->0,1->1,2-> -1
var (
	out io.Writer     = os.Stdout
	_r  io.Reader     = os.Stdin
	in  *bufio.Reader = bufio.NewReader(_r)
)

func solve() {
	Fscan(in, &n)
	for i := 1; i <= n; i++ {
		Fscan(in, &a[i])
	}
	for i := 1; i <= n; i++ {
		for j := 0; j < 3; j++ {
			f[i][j] = 1 << 30
		}
	}
	t := a[1]
	if t == -1 {
		t = 2
	}
	f[1][t] = 0
	for i := 2; i <= n; i++ {
		if a[i] == -1 {
			f[i][2] = f[i-1][2]
			f[i][1] = f[i-1][1] + 2
		} else if a[i] == 0 {
			f[i][0] = min(f[i-1][0], f[i-1][2])
			f[i][2] = f[i-1][2] + 1
			f[i][1] = f[i-1][1] + 1
		} else if a[i] == 1 {
			f[i][1] = min(f[i-1][1], min(f[i-1][0], f[i-1][2]))
			f[i][2] = f[i-1][2] + 2
			f[i][0] = f[i-1][2] + 1
		}
	}
	d := min(f[n][1], min(f[n][2], f[n][0]))
	if d >= (1 << 30) {
		Fprint(out, "BRAK")
	} else {
		Fprint(out, d)
	}
}

func min(a int64, b int64) int64 {
	if a <= b {
		return a
	}
	return b
}
func main() {
	t := 1
	//Fscan(in, &t)
	for i := 1; i <= t; i++ {
		solve()
	}
}

posted @ 2022-06-28 15:01  指引盗寇入太行  阅读(33)  评论(0编辑  收藏  举报