Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Print the only number — the minimum number of times Polycarpus has to visit the closet.
CPCPCPC
7
CCCCCCPPPPPP
4
CCCCCCPPCPPPPPPPPPP
6
CCCCCCCCCC
2
题意:有一堆明信片和照片,按顺序放在走廊里,C代表明信片,P代表照片,现在要把这堆东西拿到一个柜子里面去,规定每次只能拿一种物品且物品数目不能超过5,即每次只能拿C或S,而且最多拿5张,问最少需要拿多少次,按照题意模拟拿东西的过程即可,因为要求次数最少,所以只要每次拿尽可能多的物品数(贪心)即可。
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <string> #include <vector> #include <cmath> #include <map> using namespace std; #define LL long long int main() { char s[110]; while(gets(s)) { int len=strlen(s),ans=0; for(int i=0;i<len;i++) { int hand=0; if(s[i]=='C') { for(int j=i+1;j<i+1+4&&j<len;j++) { if(s[j]=='P') break; hand++; } } else { for(int j=i+1;j<i+1+4&&j<len;j++) { if(s[j]=='C') break; hand++; } } i+=hand; ans++; } printf("%d\n",ans); } return 0; }

本文介绍了一种物品整理策略,主人公需要将一系列明信片和照片依次放入柜子中,但每次只能拿取同类型物品且数量不超过五个。文章通过示例说明了如何采用贪心算法来最小化进入柜子的次数。
587

被折叠的 条评论
为什么被折叠?



