CF2170B Addition on a Segment

思路

正难则反,考虑从给出序列每次把一段区间减 $1$ 直到回到全 $0$。
首先从大到小排序。因为若乱序操作很可能会造成中间无法操作而两头还有剩余值的情况,非常浪费。
我们只在第一次操作时考虑最长,后面每次都使 $l=r$,若操作次数多出,则将某几次合并成一次即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<bits/stdc++.h>
#define fir first
#define sec second
#define int long long
#define pii pair<int,int>
#define fep(i,s,e) for(int i=s;i<e;i++)
#define pef(i,s,e) for(int i=s;i>e;i--)
#define rep(i,s,e) for(int i=s;i<=e;i++)
#define per(i,s,e) for(int i=s;i>=e;i--)
namespace FastIO{
template<typename T>inline void read(T &x){
x=0;int f=1;char c=getchar();
for(;!isdigit(c);c=getchar())if(c=='-')f=-1;
for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+(c^48);x*=f;
}
template<typename T,typename...Args>
inline void read(T &x,Args&...args){
read(x);
read(args...);
}
template<typename T>void print(T x){
if(x<0)x=-x,putchar('-');
if(x>9)print(x/10);
putchar((x%10)^48);
}
}
using namespace std;
using namespace FastIO;
const int N=2e5+7;
int T,n,a[N];
signed main(){
read(T);
while(T--){
read(n);
int cnt=0,num=0;
rep(i,1,n){
read(a[i]);
cnt+=a[i];
if(a[i]!=0)num++;
}
int ans=min(cnt-n+1,num);
print(ans);puts("");
}
}

赛时数组开小挂了两发,卡了一个小时。