您的位置:首页 > 其它

uva 120 Stacks of Flapjacks

2013-09-22 16:00 405 查看
模拟搬移的过程,搬移的方法是将当前剩余的球里面号数最小的排到最后面,然后再交换一次,移动到正确的位置上。

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

#define		MAX_LEN		100

int pos[MAX_LEN]; //表示大小为pos[i]的球在位置i

class cmp
{
public :
bool operator ()(const int &a, const int&b)
{
return a>b;
}
};

map<int,int,cmp> m; //保存当前的球的位置信息,first号数的球在second位置

int cmp_more(const void *a, const void *b)
{
return *((int*)b) - *((int*)a);
}

void func(int len)
{
int i, ball_num, cur_pos, right_pos;
map<int,int, cmp>::iterator it;

for(i=1; i<=len; i++)
{
ball_num = pos[i];
right_pos = i;
it = m.find(ball_num);
cur_pos = it->second;

if(cur_pos == right_pos)
continue;

if(cur_pos != len)
{
printf("%d ", cur_pos); //把号数为ball_num的球换到最后去
//更新球的位置
for(it=m.begin(); it!=m.end(); it++)
{
if(it->second>=cur_pos && it->second<=len)
{
it->second = len-(it->second-cur_pos);
}
}
}

if(len != right_pos)
{
printf("%d ", right_pos); //把号数为ball_num的球换到正确的位置上去
for(it=m.begin(); it!=m.end(); it++)
{
if(it->second>=right_pos && it->second<=len)
{
it->second = len-(it->second-right_pos);
}
}
}
}
printf("0\n");
}

int main(void)
{
int i, j, t;
char buffer[300];

while(gets(buffer) != NULL)
{
sscanf(buffer, "%d", pos+1);
for(i=0, j=2; i<strlen(buffer); i++)
if(buffer[i] == ' ')
{
sscanf(buffer+i, "%d", pos+j);
j++;
}

for(i=1; i<j-1; i++)
{
printf("%d ", pos[i]);
}
printf("%d\n", pos[i]);

for(i=1; i<=(j-1)/2; i++)
{
t = pos[i];
pos[i] = pos[j-i];
pos[j-i] = t;
}
/*
printf("length=%d\n", j-1);
for(i=1; i<=j-1; i++)
printf("%d\n", pos[i]);
*/
m.clear();
for(i=1; i<=j-1; i++)
m[pos[i]] = i;

qsort((void*)(pos+1), j-1, sizeof(int), cmp_more); //降序排列得出最后应该得到的排列方式
func(j-1);
}

return 0;
}


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