HDU 3474 Necklace 單調隊列

題意:給你一串項鍊,上面串聯着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;
}


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章