题解:P13594 『GTOI - 1A』Bath

· · 题解

题目传送门

前言

赛场上由于 WA 了很多次,所以口胡的一个做法也就顺理成章地通过了。

思路

由于这题有每个人使用水龙头的时刻 a_i,显然要结构体排序。然后观察样例,发现有时刻相同的人,所以排完序后要立刻进行同时刻温度合并,类似于离散化的操作还是很好处理的。

然后可以发现,题目要求每个人来时水温都要控制在 \left[L,R\right] 中,显然 x_i 可正可负,于是从前往后线性累加的思路直接被 hack 了。

容易发现,我们并不需要知道调节水温需要调到多少,我们只要知道调节次数即可。

考虑极端情况,由于最多可以在 L 的下限中加上 R-L 的水温或在 R 的上限中减去 R-L 水温,这已经是极限了,所以当水温加减操作不在区间 \left[L-R,R-L\right] 中时,就要调节水温了。

然后就可以用线性 O(n) 的时间复杂度处理和即可,当已经需要调节水温时,则次数 +1,并将和归零。

然后就能用这个口胡的做法通过本题。

代码

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=1e5+5;
int n,s,l,r,b[N],ans;
struct node{
    int t,x;
}a[N];
bool cmp(node x,node y){return x.t<y.t;}//按时间排序
signed main(){
    scanf("%lld%lld%lld%lld",&n,&s,&l,&r);
    for(int i=1;i<=n;i++) scanf("%lld%lld",&a[i].t,&a[i].x);
    sort(a+1,a+n+1,cmp);
    int last=0,cnt=0;
    a[0]={-1,0};
    for(int i=1;i<=n;i++){//合并同一时刻
        if(a[i].t==a[last].t) b[cnt]+=a[i].x;
        else b[++cnt]=a[i].x,last=i;
    }
    int tot=s-l,p=r-l;
    for(int i=1;i<=cnt;i++){//线性计算
        tot+=b[i];
        if(tot>p||tot<-p) ans++,tot=0;
    }printf("%lld",ans);
    return 0;
}

撒花!