B 减成一

题目地址:

https://ac.nowcoder.com/acm/contest/5758/B

基本思路:

我们求出差分数组,可以发现题意就是让我们每次将差分数组-1,+1,最后将差分数组变为第一个数为1其他数都为0的最小次数,因此实际答案就是差分数组中的正数之和减一。

参考代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define ll long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF (int)1e18

inline int read() {
  int x = 0, neg = 1; char op = getchar();
  while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
  while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
  return neg * x;
}
inline void print(int x) {
  if (x < 0) { putchar('-'); x = -x; }
  if (x >= 10) print(x / 10);
  putchar(x % 10 + '0');
}

const int maxn = 1e5 + 10;
int n,a[maxn],b[maxn];
signed main() {
  IO;
  int t;
  cin >> t;
  while (t--){
    cin >> n;
    rep(i,1,n) cin >> a[i];
    int ans = 0;
    rep(i,1,n){
      b[i] = a[i] - a[i-1];
      if(b[i] > 0) ans+=b[i];
    }
    cout << ans - 1 << '\n';
  }
  return 0;
}