stack/queue/greedy

 

林卉家

  • 資料結構
  • 先進先出(FIFO, First-In-First-Out)
  • 需引入函式庫<queue>

Queue

排隊

Queue

queue <型態> 名稱 ​宣告
​push(元素) 放入元素
​pop() 刪除第一個元素
front() 讀取最前面的元素
​empty() ​是否為空  ( 空: 1 / 有元素: 0)
​size() ​內有幾個元素

Data1.push()

Queue

Data1

queueData.pop()

Queue

Data1

  • 資料結構
  • 後進先出(LIFO, Last-In-First-Out)
  • 需引入函式庫<stack>

Stack

疊盤子

疊書本

疊熊熊(?

每個人都插隊

Stack

stack <型態> 名稱 ​宣告
​push(元素) 放入元素
​pop() 刪除第一個元素
top() 讀取最上面的元素
​empty() ​是否為空
​size() ​內有幾個元素

Stack

Data2.push(名稱)

Data2.pop()

Data2

Stack

#include <iostream>
#include <stack>

using namespace std;
int main(){

    stack <int> s;
    for(int i=1;i<=10;i++){
        s.push(i);
    }//s=[1,2,3,4,5,6,7,8,9,10]
    
    int m=s.size();
    for(int i=0;i<m;i++){
        cout<<s.top()<<endl;//依序讀取10,9,8...,1
        s.pop();//依序刪10,9,8...,1
    }
    cout<<s.size()<<"個元素"<<endl;//全部刪光剩0個元素
    return 0;
}
  • 反覆執行某個任務
  • 當下最優解

貪婪演算法Greedy

最短路徑⚠️

刪數字

1 2 3 5 6

Greedy-刪數字

4 2 9 1 3 9 6

刪4個數字變最小

4 2 9 1 7 9 6

4 2 9 1 7 9 6

4 2 9 1 7 9 6

4 2 9 1 7 9 6

剩下2 1 6

Greedy-不適用於最短路徑

指令:連通所有點

任務:挑一個最短路線鋪道路

a

b

c

d

5

6

7

11

9

e

10

~9其實不需要~

deck

By amiao

deck

  • 154