1. 程式人生 > >[USACO13JAN]畫柵欄Painting the Fence 洛谷p2205

[USACO13JAN]畫柵欄Painting the Fence 洛谷p2205

題目描述

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)

 

輸入輸出樣例

輸入樣例#1: 複製

6 2 
2 R 
6 L 
1 R 
8 L 
1 R 
2 R 

輸出樣例#1: 複製

6

說明

PS1:來源:usaco jan silver P01 想看原題的請戳http://www.usaco.org/index.php?page=viewproblem2&cpid=226)

PS2:測試資料也可以在在http://www.usaco.org/index.php?page=jan13problems上下載,還可以看到題解(不過是英文的:-D)

PS3:如果有翻譯的問題或題目的不理解,可以在問答後面留言的說。

 

#include<bits/stdc++.h>
#define f(i,l,r) for(i=(l);i<=(r);i++)
using namespace std;
const int MAXN=100005;
string ch;
int a[MAXN],s[MAXN],b[MAXN];
int n,K,ans;
int main()
{
	ios::sync_with_stdio(false);
	int i,j,d;
	cin>>n>>K;
	f(i,2,n+1){
		cin>>d>>ch;
		if(ch=="L") a[i]=a[i-1]-d;
		else a[i]=a[i-1]+d;
		s[i]=a[i];
	}
	sort(s+1,s+2+n);
	int L=unique(s+1,s+2+n)-(s+1);
	f(i,2,n+1){
		int pos1=lower_bound(s+1,s+1+L,a[i])-s;
		int pos2=lower_bound(s+1,s+1+L,a[i-1])-s;
		if(pos1>pos2) swap(pos1,pos2);
		b[pos1]++;
		b[pos2]--;
	}
	f(i,1,L-1){
		b[i]+=b[i-1];
	//	cout<<s[i]<<"GG"<<endl; 
//		cout<<b[i]<<"GGG"<<endl;
		if(b[i]>=K){
			ans+=s[i+1]-s[i];
		}
	}
	cout<<ans<<endl;
	return 0;
}