P2205 Painting the Fence
Topic description
\(Farmer\) \(John\) figured out a great way to paint the long fence next to the cowshed. (For simplicity, we think of the wall as a one-dimensional number line, and each unit of length represents a fence.) He simply dipped a brush with paint, tied it to his favorite cow \(Bessie\) , and let \ (Bessie\) passed the fence back and forth, drinking a glass of cold water on the side. (…-_-|||) \(Bessie\) All walls that pass by will be painted with a coat of paint. \(Bessie\) starts from the position on the fence \(0\) and will make \(N\) moves \((1 <= N <= 100,000\) ). For example, " \(10 L\) " means that \(Bessie\) moved left by \(10\) units. For another example, " \(15 R\) " means that \(Bessie\) moved to the right by \(15\) units. Gives a list of \(Bessie\) moves. \(FJ\) Want to know how many fences had at least \(K\) coats of paint. Notice:\(Bessie\) will move at most \(1,000,000,000\) units away from the origin.
Input and output format
Input format:
Line 1: Two integers: \(NK\)
Lines \(2...N+1\) : Each line describes a move of \(Bessie\) . (eg " \(15 L\) ")
Output format:
An integer: the number of fences that have been coated with at least \(K\) layers of paint
I don't know why, but I couldn't think of how to separate from life and death at first. .
In fact, it is only necessary to extract the range that has occurred.
Modify the interval multiple times and ask once , the difference will be faster, \(O(1)\) modify, \(O(n)\) ask.
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