uva120 stacks of flapjacks

//

//2012/2/27

//accepted

//从后向前,每次寻找最大得煎饼,如果该煎饼在pancake[0]的位置,则把该煎饼翻转到合适的位置

//否则,把该煎饼翻转大pancake[0]的位置,再把该煎饼翻转到合适的位置

//5 4 5 3 1 2这组数据,应该先找到pancake[0]位置的5,否则把pancake[2]翻转到pancake[0]就死循环了

//这一点在找最大值是控制一下

#include<iostream>

#include<algorithm>

#include<sstream>

using namespace std;

void flip(int pos,int *pancake);

int findMaxPos(int i,int *pancake);

int main()

{

     string line;

 int pancake[30];

 while(getline(cin,line))

 {

 cout<<line<<endl;

     istringstream iss(line);

 int n,i=0;

 while(iss>>pancake[i++]);

 --i;

 n=i;

 //find the max pancake's position,flip it to the n-st position and flip to the suitable position

 while(i>0)

 {

      int position=findMaxPos(i-1,pancake);

  //cout<<"***"<<position<<endl;

  if(position==i-1) {--i;continue;}

  else if(position==0) 

  {

       cout<<n-i+1<<" ";

   --i;

      flip(i,pancake);

  }

  else 

  {

  cout<<n-position<<" ";

       flip(position,pancake);

  }

 }

 cout<<0<<endl;

 }

 return 0;

}

void flip(int pos,int *pancake)

{

//flip the pancake

int i,j;

j=pos;

   if(pos&1)

   for(i=0;i<=pos/2;++i,--j)

   {

       int temp;

   temp=pancake[i];

   pancake[i]=pancake[j];

   pancake[j]=temp;

   }

   else

   for(i=0;i<=pos/2-1;++i,--j)

   {

       int temp;

   temp=pancake[i];

   pancake[i]=pancake[j];

   pancake[j]=temp;

   }

 

}

int findMaxPos(int i,int *pancake)

{//find the max position

    int j,max,pos=i;

max=pancake[i];

for(j=i;j>0;--j)

{

    if(max<=pancake[j-1])

{

max=pancake[j-1];

    pos=j-1;

}

}

return pos;

}

 

posted @ 2012-02-28 16:40  AndyDHG  阅读(181)  评论(0编辑  收藏  举报