堆中的路徑 java描述

來源:互聯網
上載者:User

標籤:bubuko   port   lan   列印   比較   取值   ring   base   完全   

將一系列給定數字插入一個初始為空白的小頂堆H[]。隨後對任意給定的下標i,列印從H[i]到根結點的路徑。

輸入格式:

每組測試第1行包含2個正整數N和M(≤1000),分別是插入元素的個數、以及需要列印的路徑條數。下一行給出區間[-10000, 10000]內的N個要被插入一個初始為空白的小頂堆的整數。最後一行給出M個下標。

輸出格式:

對輸入中給出的每個下標i,在一行中輸出從H[i]到根結點的路徑上的資料。數字間以1個空格分隔,行末不得有多餘空格。

輸入範例:
5 346 23 26 24 105 4 3
輸出範例:
24 23 1046 23 1026 10
思路:堆是一個完全二叉樹,用數組來存放堆中資料,角標為1代表堆頂。若當前角標為i,左兒子為2i,右兒子為2i+1,父節點為i/2。     每插入一個元素,把他放在完全二叉樹最後一個位置,使其與父節點比較,若小於父節點,父節點值和插入元素互換,繼續循          環比較,因為設定了哨兵arr[0]=-10001, 所以插入的資料角標最小隻可能為1,不可能為0.
import java.util.Scanner;//聲明一個堆類class heap {    //堆中資料內容有一個數組和一個表示堆大小的size    int[] arr;    int size;    //初始化堆,因為N取值是-10000到10000,取10001是為了數組能滿足題目要求,arr[0]=-10001作為哨兵,使數組從角標為1開始存放資料    //一開始堆是空的,所以size=0    public heap()    {        arr=new int[10001];        arr[0]=-10001;        size=0;    }    //向堆中插入資料,堆的資料結構是一個完全二叉樹    public void insert(int num)    {        if (size==0)        {            arr[1]=num;            size++;        }        else        {            arr[++size]=num;            //恢複t            int t=size;            while (num<arr[t/2])            {                int temp=arr[t/2];                arr[t/2]=num;                arr[t]=temp;                t=t/2;            }                }    }    //取得從給定角標到堆頂的路徑    public void road(int num)    {        while (num!=0)        {            System.out.print(arr[num]+" ");            num=num/2;        }        if (num==0)        {            System.out.println();        }    }}//測試類別class test{    public static void main(String[] args)     {        Scanner sc=new Scanner(System.in);        heap h=new heap();        int N=sc.nextInt();        int M=sc.nextInt();        for (int i=0;i<N ;i++ )        {            int num=sc.nextInt();            h.insert(num);        }                for (int i=0;i<M ;i++ )        {            int r=sc.nextInt();            h.road(r);        }    }}

列印結果:

 

 

堆中的路徑 java描述

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.