您的位置:首页 > 其它

UVA - 120 - Stacks of Flapjacks

2014-05-01 14:45 246 查看
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=98&page=show_problem&problem=56

题意:

给你一大堆饼,要求使用铲Flip(x)工具来排序,最终大饼在下,小饼在上;最后要求输出原序,以及Flip(x)的x集合。

解题:

用数组模拟Flip(x)的过程。规模不大,还可以搞。

输入到myStack[]里:用char*得输入行,再用string(char*)转成string,再用istringstream分隔成n个string,最后是atoi(string.c_str())转换成int。

把myStack[]复制到rankStack[]里,然后进行排序,得到最终饼排序。

接着进行模拟。从饼底开始,判断myStack[i]是否等于rankStack[],如果Yes就不用操作了;如No,则要先找出位置,然后把它翻到顶,再翻到指定位置。

因为饼大小可能一样,所以找位置的时候,必须从当前位置向上找【一开始从n到0找,结果老是WA】;

#include <iostream>
#include <string.h>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <stdio.h>
using namespace std;

// #define LOCAL_TEST

const int MAXN = 30;
int myStack[MAXN+1] = {0};
int rankStack[MAXN+1] = {0};

// get position of numToFind
int FindIndex(int nMin, int nMax, int numToFind)
{
for ( int i=nMax; i>=nMin; i-- )
if ( myStack[i] == numToFind )
return i;
}

// simulate the flip(x)
void FlipStack(int nMin, int nMax)
{
int tmp;
for ( int i=nMax, k=nMin; i>k; i--,k++ )
{
tmp = myStack[i];
myStack[i] = myStack[k];
myStack[k] = tmp;
} // end for
}

int main()
{
#ifdef LOCAL_TEST
freopen("f:\\in.txt", "r", stdin);
freopen("f:\\out.txt", "w+", stdout);
#endif
char strIn[1000];
vector <int> vRes;

while ( gets(strIn) )
{
// get input data to myStack[], index-0 means top, nMax-1 means bottom
string strLine(strIn);
istringstream strStream(strLine);
string strTmp;
int nMax = 0;
while ( strStream >>strTmp )
myStack[nMax++] = atoi(strTmp.c_str());

// rankStack, accending, final Res' of myStack
memcpy(rankStack, myStack, sizeof(myStack));
sort(rankStack, rankStack+nMax);

vRes.clear();
for ( int i=nMax-1; i>=0; i-- )
{
// if current pos' num is the final one, step into next pos
if ( myStack[i] == rankStack[i] )
continue;
else
{	// if current pos' num is not the final
// use FindIndex to find the pos' of "the final"
int index = FindIndex(0, i, rankStack[i]);
if ( index != 0 )
{	// if pos is not on top, flip to pos top
FlipStack(0, index);
vRes.push_back(nMax-index);
} // end if
// flip to des' pos
FlipStack(0, i);
vRes.push_back(nMax-i);
} // end else
} // end for

// print out
cout <<strLine <<'\n';
for ( vector <int>::iterator it=vRes.begin(); it!=vRes.end(); it++ )
cout <<*it <<" ";
cout <<0 <<'\n';
} // end while

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: