【線段樹】忠誠

來源:互聯網
上載者:User
描述 Description  
  老管家是一個聰明能乾的人。他為財主工作了整整10年,財主為了讓自已賬目更加清楚。要求管家每天記k次賬,由於管家聰明能幹,因而管家總是讓財主十分滿意。但是由於一些人的挑撥,財主還是對管家產生了懷疑。於是他決定用一種特別的方法來判斷管家的忠誠,他把每次的賬目按1,2,3…編號,然後不定時的問管家問題,問題是這樣的:在a到b號賬中最少的一筆是多少?為了讓管家沒時間作假他總是一次問多個問題。
     
     
  輸入格式 Input Format  
  輸入中第一行有兩個數m,n表示有m(m<=100000)筆賬,n表示有n個問題,n<=100000。
第二行為m個數,分別是賬目的錢數
後面n行分別是n個問題,每行有2個數字說明開始結束的賬目編號。
     
     
  輸出格式 Output Format  
  輸出檔案中為每個問題的答案。具體查看範例。
     
     
  範例輸入 Sample Input  
  10 3<br />1 2 3 4 5 6 7 8 9 10<br />2 7<br />3 9<br />1 10
     
     
  範例輸出 Sample Output  
  2 3 1
     
     
  時間限制 Time Limitation  
  各個測試點1s
 

一道線段樹的入門題。
每個點的Min值即為左子樹的Min值和右子樹的Min值中的較小值。

Accode:

#include <cstdio>#include <cstring>#include <cstdlib>#include <bitset>using std::min;const char fi[] = "tyvj1038.in";const char fo[] = "tyvj1038.out";const int maxN = 100010;const int maxM = 100010;const int MAX = 0x3fffff00;const int MIN = -MAX;struct SegTree {int L, R, lc, rc, Min; };SegTree tree[maxM << 1];int t[maxN];int n, m, tot;  void init_file()  {    freopen(fi, "r", stdin);    freopen(fo, "w", stdout);  }    void Build(int L, int R)  {    int Now = ++tot;    tree[Now].L = L;    tree[Now].R = R;    if (L == R)      {tree[Now].Min = t[L]; return; }    int Mid = (L + R) >> 1;    if (L < R)    {      tree[Now].lc = tot + 1;      Build(L, Mid);      tree[Now].rc = tot + 1;      Build(Mid + 1, R);    }    tree[Now].Min = min(tree[tree[Now].lc].Min,      tree[tree[Now].rc].Min);  }    int Query(int Now, int L, int R)  {    if (L <= tree[Now].L && R >= tree[Now].R)      return tree[Now].Min;    int Mid = (tree[Now].L + tree[Now].R) >> 1;    if (R <= Mid)      return Query(tree[Now].lc, L, R);//完全被左子樹包含則直接等價於左子樹的子問題。    if (Mid < L)      return Query(tree[Now].rc, L, R);//完全被右子樹包含則直接等價於右子樹的子問題。    int Lc = Query(tree[Now].lc, L, R),      Rc = Query(tree[Now].rc, L, R);    return min(Lc, Rc);  }    void work()  {    scanf("%d%d", &n, &m);    for (int i = 1; i < n + 1; ++i)      scanf("%d", t + i);    tot = 0;    Build(1, n);    for (; m; --m)    {      int L, R;      scanf("%d%d", &L, &R);      printf("%d\n", Query(1, L, R));    }  }  int main(){  init_file();  work();  exit(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.