您的位置:首页 > 其它

Codeforces 596B Wilbur and Array 【贪心】

2015-11-17 17:15 369 查看
B. Wilbur and Array

time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

Wilbur the pig is tinkering with arrays again. He has the array a1, a2, ..., an initially
consisting of n zeros. At one step, he can choose any index i and
either add 1 to all elements ai, ai + 1, ...
, an or subtract 1 from
all elements ai, ai + 1, ..., an.
His goal is to end up with the array b1, b2, ..., bn.

Of course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) —
the length of the array ai.
Initially ai = 0 for
every position i, so this array is not given in the input.

The second line of the input contains n integers b1, b2, ..., bn ( - 109 ≤ bi ≤ 109).

Output

Print the minimum number of steps that Wilbur needs to make in order to achieve ai = bi for
all i.

Sample test(s)

input
5
1 2 3 4 5


output
5


input
4
1 2 2 1


output
3


Note

In the first sample, Wilbur may successively choose indices 1, 2, 3, 4,
and 5, and add 1 to corresponding
suffixes.

In the second sample, Wilbur first chooses indices 1 and 2 and
adds 1 to corresponding suffixes, then he chooses index 4 and
subtract1.

题意:给定一个序列b[],初始序列为a[] = {0}。每次操作可以任意选择一个i,使得a[i] a[i+1] ... a
减一或者加一。问最少需要多少次操作能够使序列a[]变为序列b[]。

思路:一开始dp写了一发WA了。。。最后直接贪心模拟就AC了。

AC代码:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <vector>
#define INF 0x3f3f3f3f
#define eps 1e-4
#define MAXN (200000+10)
#define MAXM (1000000)
#define Ri(a) scanf("%d", &a)
#define Rl(a) scanf("%lld", &a)
#define Rf(a) scanf("%lf", &a)
#define Rs(a) scanf("%s", a)
#define Pi(a) printf("%d\n", (a))
#define Pf(a) printf("%lf\n", (a))
#define Pl(a) printf("%lld\n", (a))
#define Ps(a) printf("%s\n", (a))
#define W(a) while(a--)
#define CLR(a, b) memset(a, (b), sizeof(a))
#define MOD 100000007
#define LL long long
#define lson o<<1, l, mid
#define rson o<<1|1, mid+1, r
#define ll o<<1
#define rr o<<1|1
using namespace std;
LL a[MAXN];
int main()
{
int n; Ri(n);
LL ans = 0; a[0] = 0;
for(int i = 1; i <= n; i++)
{
Rl(a[i]);
ans += abs(a[i] - a[i-1]);
}
Pl(ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: