【Analysis】
这题应该贪心和DP都能过;
可以发现,一个数只能变成−1或1,令Dpi,j表示前i个数有j个变成了−1,发现转移和j的数量无关,只和奇偶性有关,令Dpi,0表示前i个数用了偶数个−1,那么方程就是
Dp[0][1] = 1e18;
Dp[i][0] = std::min(Dp[i - 1][0] + D[i][1], Dp[i - 1][1] + D[i][0]);
Dp[i][1] = std::min(Dp[i - 1][0] + D[i][0], Dp[i - 1][1] + D[i][1]);
总复杂度是O(N)
【Code】
#include <cstdio>
#include <set>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <queue>
#include <map>
namespace IO
{
inline char gc()
{
static char s[1<<20|1]={0},*p1=s,*p2=s;
return (p1==p2)&&(p2=(p1=s)+fread(s,1,1<<20,stdin),p1==p2)?EOF:*(p1++);
}
// inline char gc() { return getchar(); }
inline long long read()
{
long long ret=0;bool flag=0;char c=gc();
while ((c<'0')|(c>'9')) flag ^= !(c^'-'),c=gc();
while ((c>='0')&(c<='9')) ret=(ret<<1)+(ret<<3)+(c^'0'),c=gc();
return flag?-ret:ret;
}
char OutputAns[1<<20|1],*OutputCur = OutputAns;
inline void output()
{
OutputCur -= fwrite(OutputAns,1,OutputCur - OutputAns,stdout);
}
inline void print(long long ans)
{
char s[20]={0};
if (OutputCur - OutputAns + sprintf(s,"%I64d",ans) >> 20) output();
OutputCur += sprintf(OutputCur,"%I64d",ans);
}
inline void printc(char c)
{
if (OutputCur - OutputAns + 1 >> 20) output();
*(OutputCur++) = c;
}
}
using IO::read;
using IO::print;
using IO::printc;
using IO::output;
const int M = 1e5 + 11;
long long A[M], Dp[M][2], D[M][2];
int n;
int main(void)
{
n = read();
for (int i = 1;i <= n; ++i)
A[i] = read();
// std::sort(A + 1, A + 1 + n);
for (int i = 1;i <= n; ++i)
D[i][0] = abs(A[i] + 1), D[i][1] = abs(A[i] - 1);
Dp[0][1] = 1e18;
for (int i = 1;i <= n; ++i)
{
Dp[i][0] = std::min(Dp[i - 1][0] + D[i][1], Dp[i - 1][1] + D[i][0]);
Dp[i][1] = std::min(Dp[i - 1][0] + D[i][0], Dp[i - 1][1] + D[i][1]);
} printf("%I64d\n", Dp[n][0]);
}