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;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值