Fang Fang
Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 1167 Accepted Submission(s): 490
I promise her. We define the sequence F
F
F
F
F
Write down a serenade as a lowercase string S
Spell the serenade using the minimum number of strings in F
Following are T
The total length of strings for all test cases would not be larger than 10
For each test case, if one can not spell the serenade by using the strings in F
8 ffcfffcffcff cffcfff cffcff cffcf ffffcffcfff cffcfffcffffcfffff cff cffc
Case #1: 3 Case #2: 2 Case #3: 2 Case #4: -1 Case #5: 2 Case #6: 4 Case #7: 1 Case #8: -1HintShift the string in the first test case, we will get the string "cffffcfffcff" and it can be split into "cffff", "cfff" and "cff".
这个题目还是有个小坑的:包含除了c和f的元素。
这里思路的形成是这样的:
首先我们用一个数组来存c的位子。顺便就能统计了c的数量。
scanf("%s",a);
int n=strlen(a);
int cont=0;
int flag=0;
for(int i=0;i<n;i++)
{
if(a[i]=='c')weizi[cont++]=i;
if(a[i]!='c'&&a[i]!='f')flag=1;//如果有除c和f之外的元素,表示不能用F来表示这个字符串,
}
然后就是对很多种情况的判断:n(字符串长度)
1. 如果c的数量*3>n,那么说明不存在这样的情况。输出-1;
2.如果没有c只有f的情况,那么输出(n+1)/2;
3.只有一个c,有3个以上的f,输出1;
printf("Case #%d: ",++kase);
if(flag==1||cont*3>n)
{
printf("-1\n");
continue;
}
if(cont==0)
{
printf("%d\n",(n+1)/2);
continue;
}
if(cont==1&&n>=3)
{
printf("1\n");
continue;
}
如果不是这些个特殊情况,我们这里就要按照c的位子来处理字符串了:
我们从后边向前边遍历,如果第i个c的位子-第i-1个c的位子>2,说明是符合情况的一个子序列,output++;否则输出-1;
然后第一个c之前的f加上最后一个c之后的f的数量>2,说明是符合情况的一个子序列,否则输出-1;
int output=0;
for(int i=cont-1;i>0;i--)
{
if(weizi[i]-weizi[i-1]>2)
output++;
else
{
flag=1;
break;
}
}
if(n+weizi[0]-weizi[cont-1]>2)
output++;
else
flag=1;
if(flag==1)printf("-1\n");
else printf("%d\n",output);
最后上完整的AC代码:
#include<stdio.h>
#include<string.h>
using namespace std;
char a[10000005];
int weizi[10000005];
int main()
{
int t;
int kase=0;
scanf("%d",&t);
while(t--)
{
scanf("%s",a);
int n=strlen(a);
int cont=0;
int flag=0;
for(int i=0;i<n;i++)
{
if(a[i]=='c')weizi[cont++]=i;
if(a[i]!='c'&&a[i]!='f')flag=1;
}
printf("Case #%d: ",++kase);
if(flag==1||cont*3>n)
{
printf("-1\n");
continue;
}
if(cont==0)
{
printf("%d\n",(n+1)/2);
continue;
}
if(cont==1&&n>=3)
{
printf("1\n");
continue;
}
int output=0;
for(int i=cont-1;i>0;i--)
{
if(weizi[i]-weizi[i-1]>2)
output++;
else
{
flag=1;
break;
}
}
if(n+weizi[0]-weizi[cont-1]>2)
output++;
else
flag=1;
if(flag==1)printf("-1\n");
else printf("%d\n",output);
}
}