hdu---5455---fang fang
?
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=5455
?
題目大意:定義遞推式 F為f(0)='f',f(1)='ff',f(2)='cff',f(n)=f(n-1)+'f',給出一個(gè)首位相連的字符串s,問(wèn)組成s至少需要多少個(gè)F,如果F不能組成s,輸出-1.
分析:很明顯我們有:
(1)如果字符串含有除c和f外的其他字符的話,那么輸出-1,如果3倍c的數(shù)量大于字符串s的長(zhǎng)度,也輸出-1.
(2)如果字符串只含有f,那么結(jié)果為(len+1)/2,len為字符串s的長(zhǎng)度.
(3)對(duì)于其他情況,我們紀(jì)錄每一個(gè)c出現(xiàn)的位置,然后從后往前遍歷,如果c[i]-c[i-1]>2的話,那么就說(shuō)明這兩個(gè)c之間含有大于等于2個(gè)的f,計(jì)數(shù)器加1,否則標(biāo)記不可能.
對(duì)于第一個(gè)c之前和最后一個(gè)c之后的部分,如果相加有大于等于2個(gè)f的話,(同樣這一步也可以判斷如果只有一個(gè)c的話并且c[0]+len-c[k-1]>2也就是字符串s長(zhǎng)度大于2)計(jì)數(shù)器再加1,否則標(biāo)記不可能。
實(shí)現(xiàn)代碼如下:
#include <cstdio> #include <cstring> #include <iostream> #include <cmath> #include<vector> #include<queue> #include<algorithm>using namespace std; typedef long long LL;const int maxn=1000005; const int INF=0x3f3f3f3f;char str[maxn]; int cnt[maxn];int main() {int T, cas=1;scanf("%d", &T);while(T--){scanf("%s", str);int len=strlen(str);int k=0;int flag=1;for(int i=0; i<len; i++){if(str[i]=='c')cnt[k++]=i;if(str[i]!='c'&&str[i]!='f')flag=0;}printf("Case #%d: ", cas++);if(!flag || k*3>len){puts("-1");continue;}if(!k){printf("%d\n", (len+1)/2);continue;}int ans=0;for(int i=k-1; i>0; i--){if(cnt[i]-cnt[i-1]>2)ans++;else{flag=0;break;}}///對(duì)于第一個(gè)c之前和最后一個(gè)c之后的部分,///如果相加有大于等于2個(gè)f的話,(同樣這一步也可以判斷如果只有一個(gè)c的話并且c[0]+len-c[k-1]>2也就是字符串s長(zhǎng)度大于2)計(jì)數(shù)器再加1,if(cnt[0]+len-cnt[k-1]>2)ans++;else flag=0;///否則標(biāo)記不可能if(flag)printf("%d\n", ans);elseputs("-1");}return 0; }?
轉(zhuǎn)載于:https://www.cnblogs.com/w-y-1/p/5772138.html
總結(jié)
以上是生活随笔為你收集整理的hdu---5455---fang fang的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java用户程序
- 下一篇: js/jquery中实现图片轮播