1. 程式人生 > >樹狀數組 二維偏序【洛谷P3431】 [POI2005]AUT-The Bus

樹狀數組 二維偏序【洛谷P3431】 [POI2005]AUT-The Bus

stream 關系 iostream printf bus ret block 二維 一個

P3431 [POI2005]AUT-The Bus

Byte City 的街道形成了一個標準的棋盤網絡 – 他們要麽是北南走向要麽就是西東走向. 北南走向的路口從 1 到 n編號, 西東走向的路從1 到 m編號. 每個路口用兩個數(i, j) 表示(1 <= i <= n, 1 <= j <= m). Byte City裏有一條公交線, 在某一些路口設置了公交站點. 公交車從 (1, 1) 發車, 在(n, m)結束.公交車只能往北或往東走. 現在有一些乘客在某些站點等車. 公交車司機希望在路線中能接到盡量多的乘客.幫他想想怎麽才能接到最多的乘客.

二維偏序好題。

註意離散化y的時候記錄當前的前一個的沒變化之前的y,以此來判斷當前y與原來y的關系。

做法:我們把y離散化,根據y來建立樹狀數組。 之後枚舉n。維護到當前位置的高度y的前綴max,並且將前綴max加上當前權值加入到樹狀數組。

code:

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

inline int read(){
    int sum=0,f=1; char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
    while(ch>='0'&&ch<='9'){sum=(sum<<1)+(sum<<3)+ch-'0'; ch=getchar();}
    return sum*f;
}

const int wx=800017;

int n,m,ans,p,maxh;
int sum[wx];

struct node{
    int x,y,val,id;
}t[wx*2];

void add(int pos,int k){
    for(int i=pos;i<=maxh;i+=(i&-i)){
        sum[i]=max(sum[i],k);
    }
}

int query(int x){
    int re=0;
    for(int i=x;i>=1;i-=(i&-i)){
        re=max(re,sum[i]);
    }
    return re;
}

bool cz(node a,node b){
    if(a.y==b.y)return a.x<b.x;
    return a.y<b.y;
}

bool cmp(node a,node b){
    if(a.x==b.x)return a.y<b.y;
    return a.x<b.x;
}

int main(){
    n=read(); m=read(); p=read();
    for(int i=1;i<=p;i++){
        t[i].x=read(); t[i].y=read(); t[i].val=read(); t[i].id=i;
    }
    sort(t+1,t+1+p,cz);
    for(int i=1;i<=p;i++){
        if(t[i].y==t[i-1].y)t[i].y=t[i-1].y;
        else t[i].y=t[i-1].y+1;
        maxh=max(maxh,t[i].y);
    }
    sort(t+1,t+1+p,cmp);
    int ans=0;
    for(int i=1;i<=p;i++){
        int tmp=query(t[i].y)+t[i].val;
        add(t[i].y,tmp);
        ans=max(ans,tmp);
    }
    printf("%d\n",ans);
    return 0;
}

樹狀數組 二維偏序【洛谷P3431】 [POI2005]AUT-The Bus