您的位置:首页 > 其它

UVA 101 The blocks problem 例题整理

2017-02-28 09:05 281 查看
题目大意:编写程序按照四种不同的情况对木块进行转移

所学知识点:vector容器的运用,对于题目要求的简化抽象,四种情况,找重复进行抽象归纳。

#include<cstdio>
#include<string>
#include<vector>
#include<iostream>
//如何结束!!!!!
using namespace std;
const int maxn = 30;
int n;
vector <int> pile[maxn];   // 每个pile[i]是一个容器,就像一个二维数组(二维数组和二维向量并不一样);

int find_block(int  a, int &p, int &h)
{
for(p = 0; p < n; p++)
{
for(h = 0; h < pile[p].size(); h++)
{
if(pile[p][h] == a)
return 0;
}
}
}

int clear_blocks(int p, int h)
{
for(int i = h+1; i < pile[p].size(); i++)
{
int b = pile[p][i];
pile[b].push_back(b);    //把b塞回到原来的位置,  在pile[b] 的位置插入, 放上b
}
pile[p].resize(h+1);       //重新设置容器大小, 只保留0~h之间的元素
return 0;
}

int pile_onto(int a, int h, int b)
{
for(int i = h; i < pile[a].size(); i++)
{
pile[b].push_back(pile[a][i]);
}
pile[a].resize(h); //只需重新设置pile[a]的大小,因为pile[b]会自动扩大
return 0;
}

int printf()
{
for(int i = 0; i < n; i++)
{
cout << i << ":";
for(int j = 0; j < pile[i].size(); j++)
cout << " " << pile[i][j];
cout << endl;
}
return 0;
}

int main()
{
int a, b;
cin >> n;
string s1, s2;
for(int i; i < n; i++) pile[i].push_back(i);
while(cin >> s1)
{
if(s1 == "quit") break; //string  中内容用“ ”
cin >> a >> s2 >> b;
int pa, pb, ha, hb;
find_block(a, pa, ha);
find_block(b, pb, hb);
if(pa == pb) continue;
if(s1 == "move") clear_blocks(pa, ha);
if(s2 == "onto") clear_blocks(pb, hb);
pile_onto(pa, ha, pb);
}
printf();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva-vector