zoukankan      html  css  js  c++  java
  • [模板]笛卡尔树

    很好理解,也很好写,只要知道它的两个性质就可以自己yy了
    1.堆性质
    2.中序遍历序列就是原序列
    代码如下:

    #include <bits/stdc++.h>
    
    using namespace std;
    
    #define N 100000
    
    int n, a[N+5], fa[N+5], ch[N+5][2];
    int stk[N+5], tp;
    
    void build() {
    	for(int i = 1; i <= n; ++i) {
    		int last = 0;
    		while(tp) {
    			if(a[stk[tp]] <= a[i]) {
    				if(ch[stk[tp]][1]) ch[i][0] = ch[stk[tp]][1], fa[ch[stk[tp]][1]] = i;
    				ch[stk[tp]][1] = i, fa[i] = stk[tp];
    				break;
    			}
    			last = stk[tp--];
    		}
    		if(!tp && last) ch[i][0] = last, fa[last] = i;
    		stk[++tp] = i;
    	}
    }
    
    bool d(int x) {
    	return ch[fa[x]][1] == x;
    }
    
    int queryLeft(int x) {
    	while(fa[x] && d(x) == 0) x = fa[x]; 
    	return fa[x];
    }
    
    int queryRight(int x) {
    	while(fa[x] && d(x) == 1) x = fa[x];
    	return fa[x];
    }
    
    int main() {
    	cin >> n;
    	for(int i = 1; i <= n; ++i) cin >> a[i];
    	build();
    	for(int i = 1; i <= n; ++i)
    		printf("%d %d
    ", queryLeft(i), queryRight(i));
    	return 0;
    }
    
  • 相关阅读:
    leetcode之String to Integer (atoi)
    初次思考
    leetcode之Reverse Words in a String
    Leetcode之Database篇
    在项目中添加类
    创建项目
    配置Eclipse

    递归
    多态
  • 原文地址:https://www.cnblogs.com/dummyummy/p/10322579.html
Copyright © 2011-2022 走看看