您的位置:首页 > 其它

hdu 3474 Necklace 单调队列

2014-02-22 12:46 369 查看

Necklace

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1566 Accepted Submission(s): 455


[align=left]Problem Description[/align]
You are given a necklace consists of N beads linked as a circle. Each bead is either crystal or jade.
Now, your task is:
1. Choose an arbitrary position to cut it into a chain.
2. Choose either direction to collect it.
3. Collect all the beads in the chosen direction under the constraint that the number of crystal beads in your hand is not less than the jade at any time.
Calculate the number of ways to cut meeting the constraint

[align=left]Input[/align]
In the first line there is an integer T, indicates the number of test cases. (T<=50)
Then T lines follow, each line describes a necklace. ‘C’ stands for a crystal bead and ‘J’ stands for a jade bead. The length of necklace is between 2 and 10^6.

[align=left]Output[/align]
For each case, print “Case x: d” on a single line in which x is the number of case counted from one and d is the number of ways.

[align=left]Sample Input[/align]

2
CJCJCJ
CCJJCCJJCCJJCCJJ

[align=left]Sample Output[/align]

Case 1: 6
Case 2: 8

[align=left]Author[/align]
love8909

[align=left]Source[/align]
2010 ACM-ICPC Multi-University Training Contest(4)——Host by UESTC

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
using namespace std;

char a[2000005];
bool flag[2000002];
int s1[2000004];
typedef struct
{
int num;
int sum;
} Queue;
Queue q[2000004],tmp;
int tom;

int main()
{
int T,t;
int i,k,n,len,tail,head;
while(scanf("%d",&T)>0)
{
getchar();
for(t=1; t<=T; t++)
{
scanf("%s",a+1);
n=strlen(a+1);
len=n+n;
for(i=n+1; i<=len; i++)
a[i]=a[i-n];
for( s1[0]=0,i=1; i<=len; i++)
{
if(a[i]=='C') s1[i]=s1[i-1]+1;
else s1[i]=s1[i-1]-1;
}
memset(flag,false, sizeof(flag));
head=0;
tail=-1;
for(i=1; i<=len-1; i++)
{
tmp.sum=s1[i];
tmp.num=i;
while( head<=tail && q[tail].sum>tmp.sum ) tail--;
q[++tail]=tmp;
if( i>=n )
{
while( head<=tail && q[head].num+n<=i ) head++;
if( q[head].sum-s1[i-n]>=0 )
{
flag[ i-n+1 ]=true;
//    printf("%d ",i-n+1);
}
}
}
//    printf("\n");
s1[0]=0;
for(i=1; i<=len; i++)
{
k=len-i+1;
if(a[k]=='C') s1[i]=s1[i-1]+1;
else s1[i]=s1[i-1]-1;
}
head=0;tail=-1;
for(i=1; i<=len; i++)
{
tmp.sum=s1[i];
tmp.num=i;
while( head<=tail && q[tail].sum>tmp.sum ) tail--;
q[++tail]=tmp;
if( i>n )
{
while( head<=tail && q[head].num+n<=i ) head++;
if( q[head].sum-s1[i-n]>=0 )
{
flag[ n-(i-n)+1 ]=true;
//    printf("%d ",n-(i-n)+1);
}
}
}
//    printf("\n");
for(tom=0,i=1; i<=n; i++)
if(flag[i]==true) tom++;
printf("Case %d: %d\n",t,tom);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: