uva 120 Stacks of Flapjacks

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid;=8&page;=show_problem&problem;=56

题意:给出一个长度为n的序列(无重复元素),询问经过多少次flip(i)操作,使得序列升序排列。定义flip(i)为将1到n-i+1的元素反转... 思路:先离散化,然后注意读入....

/* ***********************************************
Author :111qqz
Created Time :2016年01月25日 星期一 10时42分46秒
File Name :code/uva/120.cpp
************************************************ */

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define fst first
#define sec second
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define ms(a,x) memset(a,x,sizeof(a))
typedef long long LL;
#define pi pair < int ,int >
#define MP make_pair

using namespace std;
const double eps = 1E-8;
const int dx4[4]={1,0,0,-1};
const int dy4[4]={0,-1,1,0};
const int inf = 0x3f3f3f3f;
const int N=105;
int n;
int a[N];
string in;

struct node
{
    int value;
    int id;
}q[N];
int pos[N];
bool cmp1(node a,node b)
{
    return a.value<b.value;
}
bool cmp2(node a,node b)
{
    return a.id<b.id;
}


void flip2( int x)
{
    for ( int i = 1 ; i <= x/2 ; i++)
    {
	swap(q[i].value,q[x+1-i].value);
    }
}

void print( int n)
{
    for ( int i = 1 ; i <= n ; i ++) printf(" %d ",q[i].value);
    printf("\n");
}

void getpos( int n)
{
    for ( int i = 1 ; i <=  n ; i++)
    {
	pos[q[i].value] = i;
    }
}
int main()
{
	#ifndef  ONLINE_JUDGE 
	freopen("code/in.txt","r",stdin);
  #endif

	while (getline(cin,in))
	{
	    ms(pos,-1); //pos[i]表示数字i的位置
	   // cout<<"oriin:"<<in<<endl;
	    int p = in.find(' ');
	    int val;
	    int cnt = 0 ; 
	    while (p!=-1)
	    {

		string tmp = in.substr(0,p);
		sscanf(tmp.c_str(),"%d",&val);
		in.erase(0,p+1);
		p = in.find(' ');
	//	cout<<"in:"<<in<<endl;
		cnt++;
		a[cnt] = val;
	    }
	    sscanf(in.c_str(),"%d",&val);
	    cnt++;
	    a[cnt]=val;

	   for ( int i = 1 ; i <= cnt ; i++) cout<<a[i]<<" ";
	   cout<<endl;
	  //hash
	    for ( int i = 1 ; i <= cnt ; i++)
	    {
		q[i].value = a[i];
		q[i].id = i ;
	    }

	    sort(q+1,q+cnt+1,cmp1);
	    int hashnum = 0;
	    for ( int i = 1 ; i <=cnt ; i++)
	    {
		hashnum++;
		q[i].value = hashnum;
	    }
	    sort(q+1,q+cnt+1,cmp2);

	    //check hash
//		for ( int i =1 ; i <= cnt ; i++) cout<<"q[i].val:"<<q[i].value<<" ";

		
	    for ( int i = 1 ; i <= cnt ; i++)
	    {
		pos[q[i].value] = i ;
	    }
	   
	   // print(cnt);
	    for ( int i = cnt ; i >=1 ; i--)
	    {
		if (pos[i]==i) continue;
		if (pos[i]==1)
		{
		    printf("%d ",cnt+1-i);
		    flip2(i);
		 //   print(cnt);
		    getpos(cnt);
		
		}
		else
		{
		    printf("%d ",cnt+1-pos[i]);
		    flip2(pos[i]);
		  //  print(cnt);
		    getpos(cnt);
		    printf("%d ",cnt+1-i);
		    flip2(i);
		  //  print(cnt);
		    getpos(cnt);
		}
	    }   
	    puts("0");

	    

	}


  #ifndef ONLINE_JUDGE  
  fclose(stdin);
  #endif
    return 0;
}