题目链接:
http://codeforces.com/problemset/problem/834/B
题目:
![](https://i-blog.csdnimg.cn/blog_migrate/bff19affcf28c61d3f52cb79722b0976.png)
It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in.
There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously.
For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are ksuch guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed.
Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened.
Two integers are given in the first string: the number of guests n and the number of guards k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26).
In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest.
Output «YES» if at least one door was unguarded during some time, and «NO» otherwise.
You can output each letter in arbitrary case (upper or lower).
5 1 AABBB
NO
5 1 ABABB
YES
题目大意:
解题思路:
代码:
#include<iostream>
#include<map>
using namespace std;
int main()
{
int n,k;
char c[1000005];
while(cin>>n>>k)
{
map<char,int>M1; //在遍历的时候用到,其实就相当于中间变量,这里不懂的话继续往下看,看完就懂了
map<char,int>M2; //存储每个门 需要通过客人 的总数量
int sum=0; //存储当前需要的 侍卫 数量
for(int i=0;i<=n-1;i++)
{
cin>>c[i];
M2[c[i]]++; //对应门(字母)的客人数量++
}
for(int i=0;i<=n-1;i++)
{
M1[c[i]]++; //对应门(字母)的客人数量++
if(M1[c[i]]==1) //说明该客人 是 要通过该门的 第一位客人
{
sum++; //既然是第一位客人,那么肯定要有侍卫去看守,sum++
if(sum>k) //如果所需客人数量 > 现有侍卫 数量,那么就没必要循环了(侍卫数量不够)
break;
}
if(M1[c[i]]==M2[c[i]]) //如果 该客人 是 通过该门的最后一位客人 ,那么这个侍卫就解放了,所需侍卫数量sum--
sum--;
}
if(sum>k) //说明侍卫数量不够
cout<<"YES"<<endl;
else //说明侍卫数量够
cout<<"NO"<<endl;
}
return 0;
}