题解 P2205 【[USACO13JAN]Painting the Fence S】
BrotherCall · · 题解
核心思想:利用差分实现离散化,求线段覆盖问题。
我们以样例为例:
线段覆盖情况如图所示。
就一般情况而言:
我们的思路为:用一个“桶(可用
而这样做,付出的时间以及空间的代价是巨大的。
从空间方面考虑:数组需要从
从时间方面考虑:光从头到尾扫描一遍,都需要
于是,我们考虑用 差分 + 离散化 实现优化:
将每条线段的左端点记录下来,并使其权值
从空间方面考虑:需要一个长度为
从时间方面考虑:读入
代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
#define ll long long
using namespace std;
int n,k;
ll next,now,last,s,sum;
char ch;
struct qz{
ll seat,num;
}QZ[200010];//数组需开到 2n
bool compare(qz x1,qz x2){
return x1.seat < x2.seat;//按端点位置从小到大排序
}
int main(){
cin>>n>>k;
for(int i=1;i<=n;i++){
cin>>next>>ch;
last = now;
if(ch == 'R'){
now += next;
QZ[i].seat = last;
QZ[i].num = 1;
QZ[i + n].seat = now;
QZ[i + n].num = -1;
}
if(ch == 'L'){
now -= next;
QZ[i].seat = now;
QZ[i].num = 1;
QZ[i + n].seat = last;
QZ[i + n].num = -1;
}
}
//以上是对每个端点的记录
sort(QZ + 1,QZ + 1 + 2 * n,compare);//将端点从小到大排序
last = QZ[1].seat;//记录第一个端点的位置
sum = QZ[1].num;//记录当前被多少条线段覆盖
ll ans = 0;
for(int i = 2;i <= 2 * n;i ++){
sum += QZ[i].num;//修改线段覆盖的条数
if(last == QZ[i].seat)continue;//如果还是同一个端点,则不计算线段长度
if(sum - QZ[i].num >= k)ans += QZ[i].seat - last;//如果线段覆盖条数 >= k,则将区间长度加在答案中
last = QZ[i].seat;
}
cout<<ans<<endl;
return 0;
}