1. 程式人生 > >演算法合集 | 神奇的笛卡爾樹

演算法合集 | 神奇的笛卡爾樹

        笛卡爾樹是一個很有意思的樹形結構,因為它同時滿足兩個性質,從key(key就是索引位置,如下圖中9的key為1,3的key為2......)來看,滿足二叉搜尋樹的特性,從value來看,滿足堆的性質。

        重點參考下圖,圖片來自維基百科,還算是能夠比較形象的說明這兩點。

        笛卡爾樹擁有這兩種特性,那麼它有什麼用途呢?

        對於HDU 1506,我們需要計算最大矩形區域,正好是笛卡爾樹最典型的用途,從上圖中,我們以任意節點K開始,K所在的最大矩形必定是K的value為高,K的右子樹最大key值減去K的key值為寬。

        笛卡爾樹比較難的地方在於構造,小編我是看了好久才把這個思路理清,這裡給出大概的思路,不懂得童鞋留言討論。

1、笛卡爾樹的構造:

(1)從第一個元素開始,從左往右遍歷陣列L

(2)將元素L[0]作為樹的根節點R

(3)for i in [a[1], a[2]...a[n]]

(4)如果a[i]小於根節點R,則將a[i]作為根節點R的父節點

(5)如果a[i]大於根節點R,則將a[i]從根節點的右節點開始尋找位置

(6)從右尋找的邏輯同根節點的對比方法

2、特性

對於樹上的每個節點,以它作為高的新矩形的面積就是以該節點為根的子樹大小乘以它的

構造原始碼:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct node_s
{
    struct node_s * l;
    struct node_s * r;
    struct node_s * p;
    int v;
}node_t;

typedef struct tree_s
{
    node_t * root;
}tree_t;

node_t * node_create(node_t * p, int v)
{
    node_t * n = (node_t*)malloc(sizeof(node_t));
    memset(n, 0, sizeof(node_t));
    n->v = v;
    n->p = p;
    return n;
}

tree_t * tree_create()
{
    tree_t * t = (tree_t*)malloc(sizeof(tree_t));
    memset(t, 0, sizeof(tree_t));
    return t;
}

void tree_insert_n(node_t * root, int v)
{
    //當前節點比根節點小,則轉換為根節點
    if(v < root->v){
        node_t * n = node_create(root->p, v);
        root->p->r = n;
        root->p = n;
        n->l = root;
    }else{
        //如果右子樹不存在,直接放置
        if(root->r == 0){
            root->r = node_create(root, v);
            return;
        }
        //當前的節點比根節點大,則從根節點的右子樹開始查詢
        tree_insert_n(root->r, v);
    }
}

void tree_insert(tree_t * t, int v)
{
    if(t->root == 0){
        t->root = node_create(0, v);
        return;
    }

    //當前節點比根節點小,則轉換為根節點
    if(v < t->root->v){
        node_t * n = node_create(0, v);
        t->root->p = n;
        n->l = t->root;
        t->root = n;
    }else{
        //如果右子樹不存在,直接放置
        if(t->root->r == 0){
            t->root->r = node_create(t->root, v);
            return;
        }
        //當前的節點比根節點大,則從根節點的右子樹開始查詢
        tree_insert_n(t->root->r, v);
    }
}

void tree_print_n(node_t * n, int level, char dir)
{
    if(!n){
        return;
    }
    for(int i=0; i<level; ++i){
        printf("---");
    }
    printf("%c--%d\n", dir, n->v);
    tree_print_n(n->l, level+1, 'L');
    tree_print_n(n->r, level+1, 'R');
}

void tree_print(tree_t * tree)
{
    tree_print_n(tree->root, 0, 'C');
    printf("\n");
}

void tree_free(tree_t * t)
{

}

int main()
{
    freopen("test.txt", "r", stdin);

    int n, height;

    while (scanf("%d", &n), n)
    {
        int arr[n];

        tree_t * tree = tree_create();

        for (int i = 0; i < n; i++)
        {
            scanf("%d", &arr[i]);
        }

        for (int i = 0; i < n; ++i)
        {
            tree_insert(tree, arr[i]);
            tree_print(tree);
        }

        tree_free(tree);

        printf("\n");
    }

    return 0;
}

        在理解了笛卡爾樹的構造之後,HDU 1506這道題就很容易理解了。具體的解題思路就不細講了,只不過在構造笛卡爾樹的時候用了陣列形式,如果一時理解不了以後再看也行,重點是把上面的程式碼弄清楚。

來看題~~翻譯看不懂直接看圖!

Problem Description 

A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3, measured in units where 1 is the width of the rectangles:

Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. The figure on the right shows the largest aligned rectangle for the depicted histogram.

Input

The input contains several test cases. Each test case describes a histogram and starts with an integer n, denoting the number of rectangles it is composed of. You may assume that 1 <= n <= 100000. Then follow n integers h1, ..., hn, where 0 <= hi <= 1000000000. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is 1. A zero follows the input for the last test case.

Output

For each test case output on a single line the area of the largest rectangle in the specified histogram. Remember that this rectangle must be aligned at the common base line.

Sample Input

7 2 1 4 5 1 3 3 
4 1000 1000 1000 1000 
0

Sample Output

8 4000

解題思路:

        參考以上。

解題程式碼:G++

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

using namespace std;

typedef long long ll;
const int N = 100000 + 10, INF = 0x3f3f3f3f;

struct node
{
    int index;
    int value;
    int parent;
    int child[2];

    friend bool operator< (node a, node b)
    {
        return a.index < b.index;
    }

    void init(int _index, int _value, int _parent)
    {
        index = _index;
        value = _value;
        parent = _parent;

        child[0] = child[1] = 0;
    }

} tree[N];

int root;
int top, stk[N];
ll ans;

//建立笛卡爾樹
int cartesian_build(int n)
{
    for (int i = 1; i <= n; i++)
    {
        int k = i - 1;

        //一直找到比i位置小的位置k
        while (tree[k].value > tree[i].value)
            k = tree[k].parent;

        //printf("i(%d - %d) k(%d - %d)\n", i, tree[i].value, k, tree[k].value);

        //將父節點的右子樹放到自己的左子樹上
        tree[i].child[0] = tree[k].child[1];
        //父節點的右子樹重新指向
        tree[k].child[1] = i;
        //設定i的父節點
        tree[i].parent = k;
        //很多人沒加這句,父節點關係就會亂掉
        tree[tree[i].child[0]].parent = i;
    }

    return tree[0].child[1];
}

int dfs(int x)
{
    if (!x)
        return 0;
    //計算最大值
    int sz = dfs(tree[x].child[0]);
    sz += dfs(tree[x].child[1]);
    ans = max(ans, (ll)(sz + 1) * tree[x].value);
    return sz + 1;
}

int main()
{
    int n, height;
    //freopen("test.txt", "r", stdin);

    while (scanf("%d", &n), n)
    {
        tree[0].init(0, 0, 0);

        for (int i = 1; i <= n; i++)
        {
            scanf("%d", &height);
            //初始化每個節點
            tree[i].init(i, height, 0);
        }

        //建立笛卡爾樹
        root = cartesian_build(n);
        //
        ans = 0;
        dfs(root);
        printf("%lld\n", ans);
    }

    return 0;
}