Noder咖啡馆里面有N个座位,每天会有若干个顾客来店里面消费,会得到相应的服务。一个顾客占一个位置,顾客离开之后位置就会空出来。如果顾客来了之后没有位置,那么顾客就会直接离开,也就得不到服务。
现在已知座位数N,以及一天之内顾客来走的顺序,请统计一下有多少顾客没有得到服务。
输入
单组测试数据。
第一行有一个整数N(1<=N<= 20 )。
第二行有若干个大写字母,表示顾客的来和走。字母是成对出现的,字母的第一次出现表示顾客来到了咖啡馆,字母的第二次出现表示该顾客离开了咖啡馆。每一种字母最多出现一对。没有座位的顾客总是在那些正在接受服务的顾客离开之前离开。
输出
输出一个整数,表示有多少顾客没有接受服务。
输入样例
样例输入1
2
ABBAJJKZKZ
样例输入2
3
GACCBDDBAGEE
输出样例
样例输出1
0
样例输出2
1
题解:
我的思路(感觉复杂了):
- flag[26+5]数组用于记录下每个字母(顾客)的出现与否,例如:flag[3] = flag[‘C’-‘A’+1] = 1,就表示顾客C在就餐,flag[3] = 0,表示不在就餐。
- res记录下剩余的位置数,cnt记录下接受不到服务的顾客个数。
- 遍历字符串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;
}