题意:给你一串项链,上面串联着C宝石和J宝石,在项链任意一点断开,从左到右或者从右到左收集宝石,且保证任意时刻C宝石的数量要大于B宝石,求满足条件的点的个数。
思路:将宝石C看做1,宝石J看做-1,若从第 i 点断开开始收集,要保证sum[i]-sum[j]的值在任意时刻都不小于0,即保证min(sum[j])-sum[i]要大于等于0,(sum[i]为1~i 的和),
这样就可以想到用单调队列来维护这个最小值了。预处理想字符串复制一份到原字符串的后面,方便后面处理。向左收集和向右收集单独写就可以了。
#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <stack>
#include <queue>
#include <cstdlib>
#include <algorithm>
using namespace std;
typedef __int64 int64;
typedef long long ll;
#define M 100005
#define N 1000005
#define max_inf 0x7f7f7f7f
#define min_inf 0x80808080
#define mod 1000000007
char str[2*N];
int num[2*N] , sum[2*N] , n;
int q[2*N] , vis[N];
int main()
{
int t , i , tcase = 1;
int n , head , tail;
scanf("%d",&t);
while (t--)
{
memset(vis , 0 , sizeof vis);
scanf("%s",str);
n = strlen(str);
for (i = n ; i < 2*n ; i++)str[i] = str[i-n];
for (sum[0] = 0 , i = 1 ; i <= 2*n ; i++)//求向右前i个的和
sum[i] = sum[i-1]+(str[i-1]=='C'?1:-1);
head = tail = 0;
for (i = 1 ; i <= n ; i++)//先将n个赋入单调队列
{
while (tail > head && sum[q[tail-1]] >= sum[i])tail--;
q[tail++] = i;
}
for (i = n+1 ; i <= 2*n ; i++)//判断第i-n个是否满足条件
{
while (i-q[head] > n)head++;
if (sum[q[head]]-sum[i-n-1] >= 0)vis[i-n] = 1;
while (tail > head && sum[q[tail-1]] >= sum[i])tail--;
q[tail++] = i;
}
//向左收集,和上面类似,需要注意的是若当前从第i个开始收集满足条件,则相当于从第i+1的位置断开的
for (sum[2*n+1] = 0 , i = 2*n ; i > 0 ; i--)
sum[i] = sum[i+1]+(str[i-1] == 'C' ? 1 : -1);
head = tail = 0;
for (i = 2*n ; i > n ; i--)
{
while (tail > head && sum[q[tail-1]] >= sum[i])tail--;
q[tail++] = i;
}
for (i = n ; i > 0 ; i--)
{
while (q[head]-i > n)head++;
if (sum[q[head]]-sum[i+n+1] >= 0)vis[i%n+1] = 1;
while (tail > head && sum[q[tail-1]] >= sum[i])tail--;
q[tail++] = i;
}
int ans = 0;
for (i = 1 ; i <= n ; i++)ans += vis[i];
printf("Case %d: %d\n",tcase++,ans);
}
return 0;
}