提高+省选-专题[二维偏序][树状数组]:P3431 [POI2005]AUT-The Bus

· · 个人记录

题目

华丽的分割线

解析

把所有车站的坐标离散化

以横坐标为第一关键字,以纵坐标为第二关键字

从前向后枚举坐标,查询以纵坐标为前缀中的最大值+当前值

每次加入以纵坐标为前缀中的最大值+当前值

因为横坐标单调,且每次查询纵坐标前缀都比当前纵坐标小

代码

#include<cstdio>
#include<algorithm>
using namespace std;
const int K=1000000;
void read(int &x)
{
    x=0;
    int f=1;
    char c;
    c=getchar();
    while((c<'0'||c>'9')&&c!='-')
    {
        c=getchar();
    }
    if(c=='-')
    {
        f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9')
    {
        x=(x<<3)+(x<<1)+(c^48);
        c=getchar();
    }
    x=x*f;
}
struct node
{
    int x;
    int y;
    int val;
    bool operator < (const node now)const;
};
bool node::operator < (const node now)const
{
    return x==now.x ? y<now.y : x<now.x;
}
node que[K];
int w[K],wm;
inline int Q(int x)
{
    return lower_bound(w+1,w+1+wm,x)-w;
}
inline int max(int x1,int x2)
{
    return x1>x2 ? x1 : x2;
}
int sum[K],k;
inline int lowbit(int i)
{
    return i&(-i);
}
void add(int pos,int val)
{
    while(pos<=wm)
    {
        sum[pos]=max(sum[pos],val); 
        pos+=lowbit(pos);
    }
    return;
}
int query(int x)
{
    int ans;
    ans=0;
    while(x>=1)
    {
        ans=max(sum[x],ans);
        x-=lowbit(x);
    }
    return ans;
}
int main()
{
    int n,m,i,ans,tmp;
    ans=0;
    read(n);
    read(m);
    read(k);
    for(i=1;i<=k;i++)
    {
        read(que[i].x);
        read(que[i].y);
        read(que[i].val);
        w[i]=que[i].y;
    }
    sort(w+1,w+1+k);
    wm=unique(w+1,w+1+k)-w-1;
    sort(que+1,que+1+k);
    for(i=1;i<=k;i++)
    {
        tmp=que[i].val+query(Q(que[i].y));
        ans=max(ans,tmp);
        add(Q(que[i].y),tmp);
    }
    printf("%d",ans);
}