首先把序列变成长度
n−1
的差分数列,那么这时的目标是将这个序列的每一个值都变为
0
。将区间操作转化成差分数列上的操作,就有:
1.将任意一个数减去或加上1(此时只要直接对前缀区间或后缀区间操作即可)。
2.将任意两个数进行相反的加减操作(此时只要直接对这个区间进行操作即可)。
设这个数列中小于0的数的和为
A
,大于0的数的和为
B
,且
A>B
(其他的情况一样)。对于
B
这一部分,可以用
B
的次数直接两两消去,而且此时其他任何的操作都是多余的。而对于剩余的
A−B
,最好的方法就是直接用
A−B
的次数每次消去一个,因为此时其他任何的操作同样是多余的。即最少的次数为
B+A−B=A
。
对于上面这个构造的过程,可以发现,在消去
B
对数之后,可以到达的数是固定的
A−B+1
个,因为在同时消去两个数时,原数列中
a1
和
an
是不变的,并且当消去了
B
对数之后,原数列会变成一个单调数列(当然,也可以考虑先消去
A−B
个数,那么最后剩余
2B
个数时会产生的数已经确定了,同样是
A−B+1
个不同的数)。有个有趣的地方就是,可以发现最后数列一定处于
a1
到
an
之间,也就是说
A−B+1=|a1−an|+1
。
ps.把变换后的数列画成阶梯状的图推导就简单很多。
文字摘自:http://blog.csdn.net/u012345506/article/details/51322028
//#include<bits/stdc++.h>
#pragma comment(linker, "/STACK:102400000,102400000")
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<math.h>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
void fre(){freopen("t.txt","r",stdin);}
template <class T1, class T2>inline void gmax(T1 &a, T2 b) { if (b>a)a = b; }
template <class T1, class T2>inline void gmin(T1 &a, T2 b) { if (b<a)a = b; }
#define ls o<<1
#define rs o<<1|1
#define MS(x,y) memset(x,y,sizeof(x))
#define MC(x, y) memcpy(x, y, sizeof(x))
typedef long long LL;
typedef unsigned long long UL;
typedef unsigned int UI;
const int INF = 0x3f3f3f3f;
int n;
void solve()
{
scanf("%d",&n);
int lst,now,first,last;
LL a = 0,b = 0;
scanf("%d",&lst); first = lst;
for(int i = 1; i < n; ++i)
{
scanf("%d",&now);
if(now - lst > 0) a += now-lst;
else b -= now-lst;
lst = now;
}
last = lst;
printf("%I64d %d\n",a>b?a:b,abs(last-first)+1);
}
int main()
{
int T,cas = 0;
scanf("%d",&T);
while(T--)
printf("Case %d: ",++cas) ,solve();
return 0;
}