隊列c++


今天是2019.7.22,距離NOIP2019還有109天

高二下學期期末考試上周結束啦

今天回歸機房的第三天

前兩天聽了兔哥講的圖論和數論

感覺目標是NOIP的話好多知識其實並不太用得上

比如FFT,二分圖匹配,擴展CRT······
今天沒課,寫點往年的NOIP原題吧

先是這道P1540機器翻譯

傳送門

很容易發現這是一道隊列+模擬的題

不過隊列的知識我已經忘得差不多了

現在復習一下

隊列是一種只能從頭進從尾出的線性數據結構

頭文件:#include<queue>

常用的函數有pop、push、front、size、empty、back······

定義一個隊列格式為queue<···> ?(···表示數據類型 比如int   ?表示變量名 是自己隨意取的)

ex:queue<int> q; 即定義一個int類型的隊列q

這里提醒一下定義隊列的時候無需說明大小,queue是動態分配空間的

(不過不要認為空間是無窮大的)

1.push

push能將一個元素壓入隊首

ex:

queue<int> q;
q.push(5);

這里將數字5壓進隊首

2.pop

pop函數能將最先入隊的元素彈出

ex:

queue<int> q;
q.push(5);
q.pop();

這里將隊中唯一元素5彈出

3.empty

empty函數是判斷隊列是否為空

空返回1,非空返回0

ex:

queue<int> q;
printf("%d ", q.empty()):
q.push(5);
printf("%d ", q.empty()):
q.pop();
printf("%d ", q.empty()):

三次依次輸出1 0 1

4.front

front函數返回的是最先進隊的元素(即隊尾元素)

ex:

 

queue<int> q;
q.push(5);
q.push(6)
printf("%d\n", q.front());

 

輸出的即為5

5.size

size函數返回的是隊中元素個數(int)

ex:

 

queue<int> q;
printf("%d "p.size());
q.push(5);
printf("%d "p.size());
q.push(6);
printf("%d "p.size());

 

輸出即為0 1 2

6.back

back函數返回的是最晚進隊的元素(即隊首元素)

ex:

queue<int> q;
q.push(5);
q.push(6);
printf("%d\n", q.back());

 

輸出的即為6

注:寫queue的函數時千萬不要忘了括號(血的教訓)

有了上面這些知識,現在我們再來做這道P1540

現在我們按照題意所述的模擬即可

代碼:

 

#include<cstdio>
#include<cstring>
#include<cctype>
#include<cstdlib>
#include<cmath>
#include<string>
#include<iostream>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#define enter puts("")
#define space putchar(' ')
using namespace std;
typedef long long ll;
int read()
{
    int ans = 0, op = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9')
    {
        if(ch == '-') op = 0;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
    {
        ans *= 10;
        ans += ch - '0';
        ch = getchar();
    }
    return op ? ans : -ans;
} 
void write(int x)
{
    if(x < 0)
    {
        x = -x;
        putchar('-');
    }
    if(x >= 10) write(x / 10);
    putchar(x % 10 + '0');
}
queue<int> q;
int n, m, a[1005], b[1005], ans;
int main()
{
    n = read(), m = read();
    for(int i = 1;i <= m;i++) a[i] = read();
    for(int i = 1;i <= m;i++)
    {
        if(b[a[i]] == 0)
        {
            if(q.size() < n)
            {
                q.push(a[i]);
                ans++;
                b[a[i]] = 1;
            }
            else
            {
                b[q.front()] = 0;
                q.pop();
                q.push(a[i]);
                ans++;
                b[a[i]] = 1;
            }
        }
    }
    write(ans);
    enter;
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM