1. 程式人生 > 其它 >2021-2-6演算法基礎課二——佇列、字串

2021-2-6演算法基礎課二——佇列、字串

技術標籤:課堂筆記

先進後出的線性資料結構。

定義

int stk[10010];
int top = 0; //指向棧頂元素的下一個位置

操作

//入棧
stk[top ++] = x; //從棧頂壓入棧
//判斷棧是否空
top == 0 //棧空
//出棧
if(top != 0) top --;

佇列

先進先出的線性資料結構。

定義

int q[10010];
//hh指向佇列的頭部,tt指向佇列的尾部
int hh = 0, tt = -1; 

操作

//入隊
q[++ tt] = x;
//佇列是否為空
hh <= tt //佇列不空
hh > tt //佇列為空
//出隊
if(hh <= tt) hh ++;

c6023 - 滑動視窗

演算法思想

  • 在視窗滑動過程中,先進入視窗元素最先滑出視窗,因此可以使用佇列儲存資料元素
  • 遍歷所有元素
    • 對於已經滑出視窗的元素,從隊頭出隊。為了能夠判斷出是否已經滑出視窗,需要在佇列中儲存每個元素在陣列中的位置。
    • 對於當前元素,需要把隊尾中所有大於等於當前元素的數都出隊
    • 將當前元素位置入隊
    • 隊頭元素就是滑動視窗的最小值,輸出隊頭即可
#include <iostream>
using namespace std;
int a[1000010];
//佇列中儲存的是元素在a陣列中的位置
int q[1000010];
int main()
{
    int n, k;
    cin >>
n >> k; for(int i = 1; i <= n; i ++) cin >> a[i]; int hh = 0, tt = -1; //求滑動視窗最小值 for(int i = 1; i <= n; i ++) { //將已經滑出視窗的元素出隊 //i - q[hh] + 1求的是視窗中元素的個數 if(hh <= tt && i - q[hh] + 1 > k) hh ++; //將隊尾大於等於當前元素a[i]的位置全部出隊
while(hh <= tt && a[q[tt]] >= a[i]) tt --; //將當前元素的位置入隊 q[++ tt] = i; //如果視窗已經劃過k個元素,輸出視窗中的最小值,即隊首元素 if(i >= k) cout << a[q[hh]] << " "; } cout << endl; hh = 0, tt = -1; //初始化新佇列的頭指標和尾指標 //求最大值 for(int i = 1; i <= n; i ++) { if(hh <= tt && i - q[hh] + 1 > k) hh ++; while(hh <= tt && a[q[tt]] <= a[i]) tt --; q[++ tt] = i; if(i >= k) cout << a[q[hh]] << " "; } return 0; }

字串

定義

string s;

操作

方法說明
size()s.size() 返回的字串中字元的個數
find()s.find(子串, [index]) 如果找到,返回子串在s中的下標;否則,返回-1
replace()s.replace(begin, len, 字串) 將s中begin位置開始長度為len的子串替換成指定字串

e2005 - 選擇你喜愛的水果

  • 使用字串陣列,儲存7種水果
  • 輸入若干行字串(包含空格),可以使用getline(cin, s);
  • 每輸入一行字串
#include <iostream>
using namespace std;
string f[7] = {"apples", "bananas", "peaches", "cherries", "pears", "oranges", "strawberries"};
int main()
{
   string s;
   //每次輸入一行字串,直到輸入結束
   while(getline(cin, s))
   {
        int idx = -1, pos = -1;
        for(int i = 0; i < 7; i ++)
        {
            pos = s.find(f[i]); //pos記錄找到的位置
            if(pos != -1)
            {
                idx = i; //記錄是第幾個水果
                break; //如果找到,則跳出迴圈
            }
        }
        //沒找到
        if(idx == -1) cout << "You must not enjoy fruit." << endl;
        else
        {
            int len = f[idx].size(); //獲取水果的長度
            s.replace(pos, len, "Brussels sprouts");
            cout << s << endl;
        }
   }
   return 0;
}