题解:P11453 [USACO24DEC] Deforestation S

· · 题解

第一次 AK 银组,发题解庆祝下。

一篇不用线段树的题解。乱搞做法。想看正解的请跳过此篇。

感觉这题比第三题难。第三题做了半小时,这题做了一个半小时。

首先我们发现可以贪心,按右端点排序,在同等线段内保留最右边的点。

然后我们就用 vector 维护有序序列,二分找个数,若不满足删点,直到满足条件。删过的跳过。

由于 vector 的 insert 非常快,所以可以通过此题。

赛时代码写的特别乱,由于我是最后做的这题,通过了之后懒得改了。代码凑合看吧。

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int T,n,k,i,j,x[N],pos,cnt;
vector<int> st;
struct Node{
    int l,r,t;
}a[N];
bool cmp(Node x,Node y){return x.r<y.r;}
int fun(int l,int r)
{
    if (lower_bound(st.begin(),st.end(),l)==st.end()||upper_bound(st.begin(),st.end(),r)==st.begin()) return 0;
    int L=lower_bound(st.begin(),st.end(),l)-st.begin();
    int R=upper_bound(st.begin(),st.end(),r)-st.begin();
    return R-L;
}
bool fd(int x)
{
    int pos=lower_bound(st.begin(),st.end(),x)-st.begin();
    if (pos>=st.size()) return false;
    return st[pos]==x;
}
void work()
{
    scanf("%d%d",&n,&k);
    for (i=1;i<=n;i++) scanf("%d",&x[i]);
    sort(x+1,x+n+1);
    for (i=1;i<=k;i++) scanf("%d%d%d",&a[i].l,&a[i].r,&a[i].t);
    sort(a+1,a+k+1,cmp);
    st.clear();
    pos=upper_bound(x+1,x+n+1,a[1].r)-x-1;
    for (i=pos-a[1].t+1;i<=pos;i++) st.insert(lower_bound(st.begin(),st.end(),x[i]),x[i]);
    for (i=2;i<=k;i++)
    {
        if (a[i].l>a[i-1].l)
        {
            if (fun(a[i].l,a[i-1].r)<a[i].t)
            {
                pos=upper_bound(x+1,x+n+1,a[i].r)-x-1;
                cnt=a[i].t-fun(a[i].l,a[i-1].r);
                for (j=pos;j>=1;j--) 
                {
                    if (fd(x[j])) continue;
                    st.insert(lower_bound(st.begin(),st.end(),x[j]),x[j]);
                    cnt--;
                    if (!cnt) break;
                }
            }
        }
        else
        {
            if (fun(a[i].l,a[i-1].r)<a[i].t)
            {
                pos=upper_bound(x+1,x+n+1,a[i].r)-x-1;
                cnt=a[i].t-fun(a[i].l,a[i-1].r);
                for (j=pos;j>=1;j--) 
                {
                    if (fd(x[j])) continue;
                    st.insert(lower_bound(st.begin(),st.end(),x[j]),x[j]);
                    cnt--;
                    if (!cnt) break;
                }
                pos=lower_bound(x+1,x+n+1,a[i].l)-x-1;
                if (cnt)
                {
                    for (j=pos;j<=n;j++)
                    {
                        if (fd(x[j])) continue;
                        st.insert(lower_bound(st.begin(),st.end(),x[j]),x[j]);
                        cnt--;
                        if (!cnt) break;
                    }
                }
            }
        }
    }
    printf("%d\n",n-st.size());
}
int main()
{
    scanf("%d",&T);
    while (T--) work();
    return 0;
}