Codeforces Round #426 (Div. 2) B题【差分数组搞一搞】

B. The Festive Evening

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 k such 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.

Input
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
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).

Input

5 1
AABBB

Output

NO

思路:从前跑一边,再从后跑一遍。记录第一次出现位置。然后套差分数组板子。

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<algorithm>
 4 
 5 using namespace std;
 6 #define N 1500000
 7 #define int long long
 8 int f[N];
 9 signed main(){
10     int n,m;
11     cin>>n>>m;
12     char str[n+100];
13     scanf("%s",str+1);
14     for(int j=0;j<26;j++){
15         char  temp='A'+j;
16         int l=0;
17         int r=0;
18         for(int i=1;i<=n;i++){
19             if(str[i]==temp){
20                 l=i;
21                 break;
22             }
23         }
24         for(int i=n;i>=1;i--){
25             if(str[i]==temp){
26                 r=i;
27                 break;
28             }
29         }
30         f[l]++;
31         f[r+1]--;
32     } 
33     for(int i=1;i<=n+15;i++)
34         f[i]+=f[i-1];
35     int maxn=0;
36     for(int i=1;i<=n;i++)
37         maxn=max(maxn,f[i]);
38     if(maxn>m){
39         printf("YES");
40     }else{
41         printf("NO");
42     }
43     return 0;
44 }
原文地址:https://www.cnblogs.com/pengge666/p/11587135.html