1. 程式人生 > >洛谷 P2205 解題報告

洛谷 P2205 解題報告

can else pac class ++ 出現 奶牛 amp tin

P2205 畫柵欄Painting the Fence

題目描述

\(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\)層塗料的柵欄數


不知道為什麽,一開始死活想不到咋離散。。

其實只需要取出現過的區間就行了。

多次修改區間一次詢問,差分會比較快,\(O(1)\)修改,\(O(n)\)詢問了。

code:

#include <cstdio>
#include <algorithm>
using namespace std;
const int N=200010;
int n,k;
int a[N];
char c;
struct node
{
    int d,loc;
    friend bool operator <(node n1,node n2)
    {
        return n1.loc<n2.loc;
    }
}t[N],f[N];
int
main() { scanf("%d%d",&n,&k); int to,now=0,cnt=0; for(int i=1;i<=n;i++) { scanf("%d %c",&to,&c); if(c==‘R‘) { now+=to,a[i]=now; t[++cnt].loc=a[i-1]; t[cnt].d=1; t[++cnt].loc=a[i]; t[cnt].d=-1; } else { now-=to,a[i]=now; t[++cnt].loc=a[i]; t[cnt].d=1; t[++cnt].loc=a[i-1]; t[cnt].d=-1; } } sort(t+1,t+1+cnt); int cnt0=0; for(int i=1;i<=cnt;i++) { if(f[cnt0].loc==t[i].loc) f[cnt0].d+=t[i].d; else f[++cnt0].d=f[cnt0-1].d+t[i].d,f[cnt0].loc=t[i].loc; } int ans=0; for(int i=1;i<cnt0;i++) if(f[i].d>=k) ans+=f[i+1].loc-f[i].loc; printf("%d\n",ans); return 0; }

2018.5.4

洛谷 P2205 解題報告