題目描述
Farmer John has devised a brilliant method to paint the long fence next to his barn (think of the fence as a one-dimensional number line). He simply attaches a paint brush to his favorite cow Bessie, and then retires to drink a cold glass of water as Bessie walks back and forth across the fence, applying paint to any segment of the fence that she walks past.
Bessie starts at position 0 on the fence and follows a sequence of N moves (1 <= N <= 100,000). Example moves might be "10 L", meaning Bessie moves 10 units to the left, or "15 R", meaning Bessie moves 15 units to the right. Given a list of all of Bessie's moves, FJ would like to know what area of the fence gets painted with at least K coats of paint. Bessie will move at most 1,000,000,000 units away from the origin during her walk.
Farmer John 想出了一個給牛棚旁的長圍牆塗色的好方法。(爲了簡單起見,我們把圍牆看做一維的數軸,每一個單位長度代表一塊柵欄)他只是簡單的把刷子蘸滿顏料,系在他最喜歡的奶牛Bessie上,然後讓Bessie來回地經過圍牆,自己則在一旁喝一杯冰鎮的涼水。(……-_-|||) Bessie 經過的所有圍牆都會被塗上一層顏料。Bessie從圍牆上的位置0出發,並將會進行N次移動(1 <= N <= 100,000)。比如說,“10 L”的意思就是Bessie向左移動了10個單位。再比如說“15 R”的意思就是Bessie向右移動了15個單位。給出一系列Bessie移動的清單。FJ 想知道有多少塊柵欄塗上了至少K層塗料。注意:Bessie最多會移動到離原點1,000,000,000單位遠的地方。
輸入輸出格式
輸入格式:* 第1行: 兩個整數: N K
* 第2...N+1 行: 每一行都描述了Bessie的一次移動。 (比如說 “15 L")
* 一個整數:被至少塗上K層塗料的柵欄數
(注意:輸出的最後一定要輸出換行符!否則會WA)
題解:
掃描線,記錄一條線段的左端點l,右端點r,當你"掃描"到l時,表示你進入了這條線段,當你掃描到r時,表示你離開了這條線段,所以這條線段的覆蓋區間爲[l,r)。
那麼在這題中也是一樣,我們記錄每個區間的左端點和右端點,並進行一次排序,然後一遍掃過去,當掃描到所在的線段>=k時,統計答案。
AC代碼:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int Maxn=100005;
int n,k,ans;
struct node{
int x,v;
}a[Maxn*2];
bool cmp(node x,node y){
return x.x<y.x;
}
int now;
int main(){
int u;
char v;
scanf("%d%d\n",&n,&k);
for(int i=1;i<=n*2;i+=2){
scanf("%d %c\n",&u,&v);
if(v=='R'){
a[i].v=1;a[i].x=now;
now+=u;
a[i+1].v=-1;a[i+1].x=now;
}
else{
a[i].v=-1;a[i].x=now;
now-=u;
a[i+1].v=1;a[i+1].x=now;
}
}
n*=2;
sort(a+1,a+1+n,cmp);
now=0;
for(int i=1;i<=n;i++){
now+=a[i].v;
if(now>=k){
ans+=a[i+1].x-a[i].x;
}
}
printf("%d\n",ans);
return 0;
}