poj 3277 – 線段樹鞏固

來源:互聯網
上載者:User

這道題目和原來求矩形覆蓋的面積差不多,這個只是它的一個特殊情況,那就是矩形底邊都在x軸上。

不多說了,每天多一點點的理解,每天深入一點點,最後你會很快滴將你的想法轉化為代碼,這也許就是所謂的碼力吧,編碼的能力。

 

//這道題目其實就是面積覆蓋,可以用原來拿到題目的源碼,稍微改一下就ok//但是還是想學習一下,自己寫寫代碼,深入瞭解線段樹,希望大家能看明白//其實有時候動手畫一棵樹,然後類比幾個點,可以加深你對線段樹的理解#include <iostream>#include <cstdio>#include <algorithm>using namespace std;int A[40001],B[40001],H[40001],sLine[80004];int N = 0,n;struct Tree{int l,r,h;}tree[300000];//每次線段樹的題目都是這樣建樹滴,所以這個過程相信你並不陌生void build (int t, int l, int r){tree[t].l = l;tree[t].r = r;if (l == r - 1){return;}int mid = (l + r) >> 1;build(2 * t, l, mid);build(2 * t + 1, mid, r);}//同樣每次都會有插入樹的操作,更新一些資訊,這個要具體問題具體分析void insert(int t, int i, int l, int r){if (sLine[tree[t].l] == l && sLine[tree[t].r] == r){if (tree[t].h < H[i]){tree[t].h = H[i];}                return;}int mid = sLine[(tree[t].l + tree[t].r) >> 1];if (r <= mid){insert(2 * t, i, l, r);}else if (l >= mid){insert(2 * t + 1, i, l, r);}else{insert(2 * t, i, l, mid);insert(2 * t + 1, i, mid, r);}}//求面積,注意這裡之所以要有一個高度的參數,是因為insert的時候,並沒有將高度更新到葉子節點,所以,葉子節點的高度並不一定是最大的高度,所以要用父節點的高度來更新。long long count(int t,  int h){if (h > tree[t].h){tree[t].h = h;}if (tree[t].r - tree[t].l == 1){return (long long)(sLine[tree[t].r] - sLine[tree[t].l]) * tree[t].h;}return count(2 * t, tree[t].h) + count(2 * t + 1, tree[t].h);}int main(){scanf("%d", &n);for (int i = 1; i <= n; ++ i){scanf("%d %d %d", &A[i], &B[i], &H[i]);sLine[++ N] = A[i];sLine[++ N] = B[i];}sort(sLine + 1, sLine + N + 1);//去掉重複的掃描線N = unique(sLine + 1, sLine + N + 1) - sLine - 1;build(1, 1, N);for (int i = 1; i <= n; ++ i){insert(1, i, A[i], B[i]);}printf("%lld\n", count(1, 0));return 0;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.