BZOJ4919 大根堆 [树上LIS]

大根堆

题目描述见链接 .


color{red}{正解部分}

树上 LISLIS 问题,

使用 std::multiset<int> st 维护当前子树内所有可能的 LISLIS 结尾, 从前往后 LISLIS结尾 对应的长度递增 .

子树之间互不影响, 只需考虑子树根节点 uu 对子树内的影响, 类比 序列LISLIS 的做法,

  • wuw_ust中为没有出现过的最大值, 则直接加入 st中 .
  • 否则考虑将 wuw_u 作为一个新的可能的 LISLIS结尾, 替换掉前面某个正好 大于等于 wuw_uLISLIS结尾 . (此时 LISLIS总长度 并没有变化)

color{red}{实现部分}

#include<bits/stdc++.h>
#define reg register

int read(){
        char c;
        int s = 0, flag = 1;
        while((c=getchar()) && !isdigit(c))
                if(c == '-'){ flag = -1, c = getchar(); break ; }
        while(isdigit(c)) s = s*10 + c-'0', c = getchar();
        return s * flag;
}

const int maxn = 200005;

int N;
int M;
int num0;
int A[maxn];
int head[maxn];

std::multiset <int> st[maxn];
std::multiset <int>::iterator it;

struct Edge{ int nxt, to; } edge[maxn << 1];

void Add(int from, int to){ edge[++ num0] = (Edge){ head[from], to }; head[from] = num0; }

void DFS(int k, int fa){
        for(reg int i = head[k]; i; i = edge[i].nxt){
                int to = edge[i].to;
                if(to == fa) continue ;
                DFS(to, k);
                if(st[to].size() > st[k].size()) std::swap(st[k], st[to]);
                for(it = st[to].begin(); it != st[to].end(); it ++) st[k].insert(*it);
                st[to].clear();
        }
        it = st[k].lower_bound(A[k]);
        if(it != st[k].end()) st[k].erase(it);
        st[k].insert(A[k]);
}

int main(){
        N = read();
        for(reg int i = 1; i <= N; i ++){
                A[i] = read(); int x = read();
                if(!x) continue ;
                Add(x, i), Add(i, x);
        }
        DFS(1, 0); printf("%d
", st[1].size());
        return 0;
}
原文地址:https://www.cnblogs.com/zbr162/p/11822399.html