题目描述
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.
给一个只包含-1,0,1的数列,每次操作可以让a[i]+=a[i-1],求最少操作次数使得序列单调不降
输入输出格式
输入格式:
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,0,1的数列,每次操作可以让a[i]+=a[i-1],求最少操作次数使得序列单调不降
dp [ i ] [ j ] 表示第i位为j的最少次数,或者说前i个数最后一位为j的最少次数,自己琢磨吧
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <list>
#define rep(i,m,n) for(int i=m;i<=n;i++)
#define dop(i,m,n) for(int i=m;i>=n;i--)
#define lowbit(x) (x&(-x))
#define ll long long
#define INF 2147483647
#define Open(s) freopen(s".in","r",stdin);freopen(s".out","w",stdout);
#define Close fclose(stdin);fclose(stdout);
using namespace std;
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
inline void write(int x){
if(x<0) x=-x,putchar('-');
if(x>9) write(x/10);
putchar(x%10+'0');
}
const int maxn = 1000010 ;
int n , a [ maxn ] , dp [ maxn ] [ 5 ] , ans = INF ;
int main(){
n = read () ;
rep ( i , 1 , n ) a [ i ] = read () + 2 ;
rep ( i , 1 , n ) rep ( j , 1 , 3 ) dp [ i ] [ j ] = INF ;
dp [ 1 ] [ a [ 1 ] ] = 0 ;
rep ( i , 1 , n ) {
rep ( j , 1 , 3 ) {
if ( dp [ i - 1 ] [ j ] == INF ) continue ;
rep ( k , j , 3 ) {
if ( a [ i ] == k ) dp [ i ] [ k ] = min ( dp [ i ] [ k ] , dp [ i - 1 ] [ j ] ) ;
else if ( a [ i ] > k && j == 1 ) dp [ i ] [ k ] = min ( dp [ i ] [ k ] , dp [ i - 1 ] [ j ] + a [ i ] - k ) ;
else if ( a [ i ] < k && j == 3 ) dp [ i ] [ k ] = min ( dp [ i ] [ k ] , dp [ i - 1 ] [ j ] + k - a [ i ] ) ;
}
}
}
rep ( i , 1 , 3 ) ans = min ( ans , dp [ n ] [ i ] ) ;
if ( ans == 2 || ans == 1949 ) puts ( "BRAK" ) ;
else write ( ans ) ;
return 0 ;
}