[USACO13JAN]Painting the Fence【扫描线】

Pro

Luogu2205

Sol

表示自己独立想不到这个解法……

所谓扫描线,就是不断地移动,移动到一条线段的左端点时 + 1 ,移动到右端点时 1 。我们用 n o w 表示覆盖的有多少条线段,把每一个区间按照坐标排好序之后,如果发现满足我们的条件,就直接加上两个点之间的点的数量。

Code

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

struct Node {
    int opt , val;
    bool operator < (const Node &a) const {
        return opt < a.opt;
    }
};
Node seg[200005];
int n , m , top , now , ans;

int main() {
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++) {
        int len;char c;
        cin>>len>>c;
        if(c == 'R') {
            seg[++top] = (Node){now , +1};
            seg[++top] = (Node){now+=len , -1};
        } else {
            seg[++top] = (Node){now , -1};
            seg[++top] = (Node){now-=len , 1};
        }
    }
    sort(seg+1 , seg+top+1);
    now = seg[1].val;
    for(int i=2; i<=top; i++) {
        if(now >= m)
            ans += (seg[i].opt - seg[i-1].opt);
        now += seg[i].val;
    }
    printf("%d",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43061009/article/details/82119234