51Nod 1912 咖啡館 c/c++題解

題目描述

Noder咖啡館裏面有N個座位,每天會有若干個顧客來店裏面消費,會得到相應的服務。一個顧客佔一個位置,顧客離開之後位置就會空出來。如果顧客來了之後沒有位置,那麼顧客就會直接離開,也就得不到服務。
現在已知座位數N,以及一天之內顧客來走的順序,請統計一下有多少顧客沒有得到服務。
輸入
單組測試數據。
第一行有一個整數N(1<=N<= 20 )。
第二行有若干個大寫字母,表示顧客的來和走。字母是成對出現的,字母的第一次出現表示顧客來到了咖啡館,字母的第二次出現表示該顧客離開了咖啡館。每一種字母最多出現一對。沒有座位的顧客總是在那些正在接受服務的顧客離開之前離開。
輸出
輸出一個整數,表示有多少顧客沒有接受服務。
輸入樣例
樣例輸入1
2
ABBAJJKZKZ
樣例輸入2
3
GACCBDDBAGEE
輸出樣例
樣例輸出1
0
樣例輸出2
1

題解:

我的思路(感覺複雜了):

  1. flag[26+5]數組用於記錄下每個字母(顧客)的出現與否,例如:flag[3] = flag[‘C’-‘A’+1] = 1,就表示顧客C在就餐,flag[3] = 0,表示不在就餐。
  2. res記錄下剩餘的位置數,cnt記錄下接受不到服務的顧客個數。
  3. 遍歷字符串str,每次拿到一個顧客c = str[i] - 'A' + 1,判斷:
    if(!flag[c] && res >= 1):表示這個顧客沒有出現過,而且還有剩餘的位置,那麼就標記爲出現過flag[c] = 1,剩餘位置數res--
    if(!flag[c] && res < 1):表示沒有剩餘的位置了,那麼也就說明有一個顧客接收不到服務了cnt++而且這個顧客找不到座位就會立馬退出,所以下一個字母不變,那麼可以直接i++,再加上for裏面的i++,就會跳到這個字母的後面兩個位置處了
    flag[c]:表示這個顧客出現過了,所以已經在就餐了,然後第二次出現就代表要走了,標記flag[c] = 0,res++

代碼:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
int n;
string str;
int res;
int flag[26+5];

int main()
{
    /*
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    */

    cin >> n;
    cin >> str;
    int cnt = 0;// 顧客接受不到服務的個數
    res = n;// 剩餘的位置數
    for(int i = 0; i < (int)str.length(); i++)
    {
        int c = str[i] - 'A' + 1;
        if(!flag[c])
        {
            if(res >= 1)
            {
                flag[c] = 1; res--;
            }
            else
            {
                cnt++;
                i++;// 找不到座位會馬上退出,所以下一個也肯定是一樣的c
            }
        }
        else
        {
            flag[c] = 0;
            res++;
        }
    }
    cout << cnt << endl;

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章