木块问题(The Blocks Problem, UVa 101)

本文介绍了一个使用迭代器处理数据堆栈的应用案例。通过定义多种操作如move_onto、pile_over等,实现对不同堆栈中元素的操作转移。利用C++标准模板库中的vector和迭代器完成一系列指令,包括元素的查找、移动等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我用了迭代器

// uva101.cpp
#include <vector>
#include <iostream>
#include <string>
using namespace std;
const int MAX = 30;
vector<int> pile[MAX];
vector<int> tmp;
int n;
int find(int a){
    for(int b = 0; b < n; b++)
        for(vector<int>::iterator yy = pile[b].begin(); yy != pile[b].end(); yy++)
            if (*yy == a) return b;
    return -1;
}
void return_pile(int a){
    int xx = find(a);
    while(pile[xx].back() != a){
        pile[ pile[xx].back() ].push_back( pile[xx].back() );
        pile[xx].pop_back();
    }
}

void pile_over(int a, int b) {
    int pa = find(a);
    int pb = find(b);
    tmp.clear();
    while(true) {
        tmp.push_back( pile[pa].back() );
        pile[pa].pop_back();
        if (tmp.back() == a) break;
    }
    while(!tmp.empty() ){
        pile[pb].push_back( tmp.back() );
        tmp.pop_back();
    }
}
void pile_onto(int a, int b){
    return_pile(b);
    pile_over(a, b);
}
void move_onto(int a, int b){
    return_pile(a);
    return_pile(b);
    pile_over(a, b);
}
void move_over(int a, int b){
    return_pile(a);
    pile_over(a, b);
}
void print_pile(int n){
    for(int b = 0; b < n; b++){
        cout << b << ":";
        for (vector<int>::iterator i = pile[b].begin(); i != pile[b].end(); ++i)
        {
            cout << " " << *i;
        }
        cout << endl;
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin >> n;
    for (int i = 0; i < n ; i++){
        pile[i].clear();
    }
    for(int i = 0; i < n; i++){
        pile[i].push_back(i);
    }
    string cmd1, cmd2;
    while((cin >> cmd1) && cmd1 != "quit"){
        int a, b;
        cin >> a >> cmd2 >> b;
        int pa = find(a), pb = find(b);
        if (pa == pb) continue;  // a, b can not be in the same pile
        if(cmd1 == "move") {
            if (cmd2 == "onto") move_onto(a, b);
            else move_over(a, b);
        }
        else{
            if (cmd2 == "onto") pile_onto(a, b);
            else pile_over(a, b);
        }
    }
    print_pile(n);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值