洛谷P3558 [POI2013]BAJ-Bytecomputer
? 解题记录 ? ? 洛谷 ? ? 动态规划 ?    2018-06-24 22:31:38    496    0    0

题目描述

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: 复制
6
-1 1 0 -1 0 1
输出样例#1: 复制
3

说明

给一个只包含-1,0,1的数列,每次操作可以让a[i]+=a[i-1],求最少操作次数使得序列单调不降

很板的一眼DP题,直接dp[i][3]表示在第i个位置的时候最后是0,-1,1的最小花费是多少就好了,总复杂度O(n)

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1e6 + 5, inf = 0x3f3f3f3f;
int n, dp[maxn][3], num[maxn], ans;

int main() {
    scanf("%d", &n);
    memset(dp, 0x3f, sizeof(dp));
    for(register int i = 1; i <= n; ++i) scanf("%d", &num[i]);
    dp[1][num[1] + 1] = 0;
    for(register int i = 2; i <= n; ++i) {
        for(register int j = 0; j < 3; ++j) {
            if((j - 1) + num[i] < 2 && (j - 1) + num[i] > -2 && (j - 1) + num[i] >= j - 1)
                dp[i][j + num[i]] = min(dp[i][j + num[i]], dp[i - 1][j] + 1);
            if(2 * (j - 1) + num[i] < 2 && 2 * (j - 1) + num[i] > -2 && 2 * (j - 1) + num[i] >= j - 1)
                dp[i][2 * (j - 1) + num[i] + 1] = min(dp[i][2 * (j - 1) + num[i] + 1], dp[i - 1][j] + 2);
            if(num[i] >= j - 1) 
                dp[i][num[i] + 1] = min(dp[i][num[i] + 1], dp[i - 1][j]);
        }
    }
    ans = min(dp[n][0], min(dp[n][1], dp[n][2]));
    printf(ans == inf ? "BRAK" : "%d", ans);
    return 0;
} 

P3558 [POI2013]BAJ-Bytecomputer


上一篇: 洛谷P3537 [POI2012]SZA-Cloakroom

下一篇: 从Parasprite说起:排列与组合数

496 人读过
立即登录, 发表评论.
没有帐号? 立即注册
0 条评论
文档导航