题目描述
Bitaro received a string S of length N for his birthday present. String S consists of three kinds of characters,J, O and I.
For each positive integer K, we will call the string which consists of K J’s, K O’s, and K I’s in this order JOI-string of level K. For example, JJOOII is a JOI-string of level 2.
Bitaro likes a JOI-string of level K, so he is going to make a JOI-string of level K from string S by using the following three operations any number of times in arbitrary order:
Operation 1 Bitaro deletes the first character of S .
Operation 2 Bitaro deletes the last character of S .
Operation 3 Bitaro deletes a character of S which is neither the first nor the last.
Because using Operation 3 is time-consuming, Bitaro wants to make a JOI-string of level K with as small number of Operation 3 as possible.
Write a program which, given a string S of length N and a positive integer K, prints the smallest number of Operation 3 required to make a JOI-string of level K from S . If it is impossible to make a JOI-string of level K with the operations, print − 1 instead.
输入
Read the following data from the standard input. N and K are integers. S is a string.
N K
S
Constraints
• 3 ≤ N ≤ 200 000.
• 1 ≤ K ≤ N/3.
• S is a string of length N which consists of J, O and I.
输出
Write one line to the standard output. The output should contain the smallest number of Operation 3 required to make a JOI-string of level K from S . If it is impossible to make a JOI-string of level K, print − 1 instead.
样例输入 Copy
【样例1】
10 2
OJIJOIOIIJ
【样例2】
9 3
JJJOOOIII
【样例3】
9 1
IIIOOOJJJ
样例输出 Copy
【样例1】
2
【样例2】
0
【样例3】
-1
提示
样例1解释
You can make a JOI-string of level K from string S by the following operations:
- You use Operation 1 and S becomes JIJOIOIIJ.
- You use Operation 2 and S becomes JIJOIOII.
- You use Operation 3 to remove the second character and S becomes JJOIOII.
- You use Operation 3 to remove the fourth character and S becomes JJOOII.
It is impossible to make a JOI-string of level K with using Operation 3 less than twice, so you should print 2.
样例2解释
You need not use an operation.
样例3解释
In this sample, it is impossible to make a JOI-string of level 1 from string S .
解析:
维护三个数组.
数组维护的是:处理i的时候跳到哪个位置使得之间有k个 ‘J’,‘O’,‘I’;
用队列处理
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+1000;
int n,k;
int a[N];
int nj[N],no[N],ni[N];
char s[N];
void get(int nx[],char c)
{
queue<int>q;int l=0;
for(int i=1;i<=n;i++) //预处理i位置跳到哪使得之间有k个 J,O,I;
{
if(s[i]==c)
{
q.push(i);
if(q.size()==k)
{
for(int j=l+1;j<=q.front();j++) nx[j]=i;
l=q.front();q.pop();
}
}
}
for(int i=l+1;i<=n;i++) nx[i]=1e9;
}
int main()
{
scanf("%d %d",&n,&k);
scanf("%s",(s+1));
get(nj,'J');get(no,'O');get(ni,'I');
int ans=1e9;
for(int i=1;i<=n;i++)
{
int j=nj[i]; if(j>n) continue;
j=no[j];if(j>n) continue;
j=ni[j];if(j>n) continue;
ans=min(ans,j-i+1-3*k);
}
if(ans==1e9) cout<<-1<<endl;
else cout<<ans<<endl;
}