Problem Description
Fang Fang says she wants to be remembered.
I promise her. We define the sequence F of strings.
F0 = ‘‘f”,
F1 = ‘‘ff”,
F2 = ‘‘cff”,
Fn = Fn−1 + ‘‘f”, for n > 2
Write down a serenade as a lowercase string S in a circle, in a loop that never ends.
Spell the serenade using the minimum number of strings in F, or nothing could be done but put her away in cold wilderness.
Input
An positive integer T, indicating there are T test cases.
Following are T lines, each line contains an string S as introduced above.
The total length of strings for all test cases would not be larger than 106.
Output
The output contains exactly T lines.
For each test case, if one can not spell the serenade by using the strings in F, output −1. Otherwise, output the minimum number of strings in F to split S according to aforementioned rules. Repetitive strings should be counted repeatedly.
Sample Input
8
ffcfffcffcff
cffcfff
cffcff
cffcf
ffffcffcfff
cffcfffcffffcfffff
cff
cffc
Sample Output
Case #1: 3
Case #2: 2
Case #3: 2
Case #4: -1
Case #5: 2
Case #6: 4
Case #7: 1
Case #8: -1
Hint
Shift the string in the first test case, we will get the string “cffffcfffcff”
and it can be split into “cffff”, “cfff” and “cff”.
題意:給出定義遞推式F為:f(0)=’f’,f(1)=’ff’,f(2)=’cff’,f(n)=f(n-1)+’f’(n>2);
然後給出一個首位相連的字串s,問組成s至少需要多少個f[i],如果f不能組成s,輸出-1;
題解:
分為以下幾種情況來考慮:
(1)如果字串含有除c和f外的其他字元的話,那麼輸出-1,如果3倍c的數量大於字串s的長度,也輸出-1.
(2)如果字串只含有f,那麼結果為(len+1)/2,len為字串s的長度.
(3)如果s中只含有一個c,且len大於等於3,那麼結果為1.
(4)紀錄每一個c出現的位置,從後往前遍曆,如果c[i]-c[i-1]>2,說明這兩個c之間含有大於等於2個的f,計數器加1,否則標記不可能.對於第一個c之前和最後一個c之後的部分,如果相加有大於等於2個f的話,計數器再加1,否則標記不可能。
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define N 1000010char str[N];int c[N];int main(){ int T,cas=1,i; scanf("%d",&T); while(T--) { scanf("%s",str); int flag=1; int len = strlen(str); int cnt=0; for(i=0;i<len;i++) { if(str[i]=='c') c[cnt++]=i; if(str[i]!='c' && str[i]!='f') flag=0; } printf("Case #%d: ",cas++); if(flag==0 || cnt*3>len) { printf("-1\n"); } else if(cnt==0) { printf("%d\n",(len+1)/2); } else if(cnt==1 && len>=3) { printf("1\n"); } else { int ans=0; int f=1; for(i=cnt-1;i>0;i--) { if(c[i]-c[i-1]>2) ans++; else { f=0; break; } } if(c[0]+len-c[cnt-1]>2) ans++; else f=0; if(f) printf("%d\n",ans); else printf("-1\n"); } } return 0;}