朱色虫居
Pages
Home
Featured Posts
2007/05/30
120-Stacks of Flapjacks
/*
"Stacks of Flapjacks"
Level:5.5
Date:2007/5/29
技巧:
input:利用getline讀入字串,再用strtok()將空白清除。
process:
1.將最大的元素先reverse至top of stack
2.再將top of stack reverse到bottom
3.將次大元素reverse至top of stack
4.再將top of stack reverse到bottom-1
repeat...until (bottom ==1)
Bill Gaze大一寫的論文,就是提出多種Flapjacks problem及解法,
後來主要被應用在生物資訊的DNA字串比對。
*/
#include
#include
#include
#include
using namespace std;
int main(){
string str;
char *s, *str2char;
vector
ivec;
vector
::iterator iter;
vector
::iterator iter_end;
vector
::iterator spatula; //要翻的煎餅,翻的位置要+1,
int max; //暫存bottom以上最大的element.
int bottom; //bottom以上皆未排序.
while(getline(cin,str)){
str2char = new char[str.size()+1];
strcpy(str2char, str.c_str());
ivec.clear();
//將input string清掉空白,並一一丟入int array
for(s = strtok(str2char, " "); s!= NULL; s=strtok(NULL, " ")){
ivec.push_back(atoi(s));
}
iter = ivec.begin();
iter_end = ivec.end();
bottom = ivec.size();
cout << str << endl; while(1){ if(bottom ==1){ cout << "0" << endl; break; } iter = ivec.begin(); //如果top element是最大者,便從bottom以上做reverse,並將bottom向上移動一層 if(ivec[0] == (max = *max_element(iter, iter+bottom))){ if(ivec[0] == ivec[bottom-1]){ --bottom; continue; } reverse(iter, iter+bottom); cout << ivec.size()-bottom+1 << " "; --bottom; } /*否則從bottom以上找最大元素,並從最大元素下做reverse, *以將最大元素移至top element. */ else{ spatula = find(iter, iter+bottom, max); /*如果最大元素正好在bottom的上方, *便無須reverse,並將bottom向上移動一層. */ if(ivec[spatula-iter] == ivec[bottom-1]){ --bottom; continue; } reverse(iter, spatula+1); cout << ivec.size() - (spatula-iter) << " "; } } } }
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment