【动态规划】BAJ-Bytecomputer

87 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第10天,点击查看活动详情

[POI2013]BAJ-Bytecomputer

题面翻译

给定一个长度为 nn 的只包含 1,0,1-1,0,1 的数列 aa,每次操作可以使 aiai+ai1a_i\gets a_i+a_{i-1},求最少操作次数使得序列单调不降。如果不可能通过该操作使得序列单调不降,请输出 BRAK

数据范围:1n1061\le n\le 10^6

题目描述

A sequence of integers from the set is given.

The bytecomputer is a device that allows the following operation on the sequence:

incrementing by for any .

There is no limit on the range of integers the bytecomputer can store, i.e., each can (in principle) have arbitrarily small or large value.

Program the bytecomputer so that it transforms the input sequence into a non-decreasing sequence (i.e., such that ) with the minimum number of operations.

输入格式

The first line of the standard input holds a single integer (), the number of elements in the (bytecomputer's) input sequence.

The second line contains integers () that are the successive elements of the (bytecomputer's) input sequence, separated by single spaces.

In tests worth 24% of the total points it holds that , and in tests worth 48% of the total points it holds that .

输出格式

The first and only line of the standard output should give one integer, the minimum number of operations the bytecomputer has to perform to make its input sequence non-decreasing, of the single word BRAK (Polish for none) if obtaining such a sequence is impossible.

样例 #1

样例输入 #1

6
-1 1 0 -1 0 1

样例输出 #1

3
#include<bits/stdc++.h>
using namespace std;
int n,a[1000001],f[1000001][4];
inline int read(){
	int x=0,f=1;char ch=getchar();
	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
	while (isdigit(ch)){x=(x<<1)+(x<<3)+ch-48;ch=getchar();}
	return x*f;
}
int main(){
	n=read();
	for (int i=1;i<=n;i++){
		a[i]=read();
	}
	memset(f,0x3f,sizeof(f));
	f[1][a[1]+1]=0;
	for (int i=2;i<=n;i++){
		if (a[i]==1){
			f[i][0]=f[i-1][0]+2;
			f[i][1]=f[i-1][0]+1;
			f[i][2]=min(f[i-1][0],min(f[i-1][1],f[i-1][2]));
		}else if (a[i]==0){
			f[i][0]=f[i-1][0]+1;
			f[i][1]=min(f[i-1][0],f[i-1][1]);
			f[i][2]=f[i-1][2]+1;
		}else{
			f[i][0]=f[i-1][0];
			f[i][2]=f[i-1][2]+2;
		}
	}
	if (min(min(f[n][0],f[n][1]),f[n][2])==f[0][0]){
		printf("BRAK");
	}else{
		printf("%d",min(min(f[n][0],f[n][1]),f[n][2]));
	}
}