C++ vector用法积累

1. vector的初始化

2. vector基本操作

2.1 vector属性

size
resize

2.2 vector操作

  • 插入

    在最后插入一个元素

push_back()
  • 删除

    在最后删除一个元素

pop_back()

uva 101 木块问题

题目大意

输入n,得到编号为0n-1的木块,分别摆放在顺序排列编号为0n-1的位置。现对这些木块进行操作,操作分为四种。

  1. move a onto b:把木块a、b上的木块放回各自的原位,再把a放到b上;
  2. move a over b:把a上的木块放回各自的原位,再把a发到含b的堆上;
  3. pile a onto b:把b上的木块放回各自的原位,再把a连同a上的木块移到b上;
  4. pile a over b:把a连同a上木块移到含b的堆上。

    当输入quit时,结束操作并输出0~n-1的位置上的木块情况

Sample Input

10

move 9 onto 1

move 8 over 1

move 7 over 1

move 6 over 1

pile 8 over 6

pile 8 over 5

move 2 over 1

move 4 over 9

quit

Sample Output

0: 0

1: 1 9 2 4

2:

3: 3

4:

5: 5 8 7 6

6:

7:

8:

9:

#include<cstdio>
#include<algorithm>
#include<vector>
#include<string>
#include<iostream>
using namespace std;
/*
move a onto b:把a和b上方的木块全部归位,然后把a放到b上方
move a over b:把a上方的木块全部归位,然后把a放到b木块所在的顶部
pile a onto b:把b上方的木块全部归位,然后把a及以上的木块整体放到b上面。
pile a over b:把a和a以上的木块全部放到b所在的木块堆的顶部。
*/
const int MAXC=30;
int n;
vector<int> pile[MAXC];
//用来查找a具体在哪个堆的,要得到两个数据,堆和高度
void find_block(int a,int& i,int& j){
    for(i=0;i<n;i++){
        for(j=0;j<pile[i].size();j++){
            if(pile[i][j] == a)
            return;
        }
    }
}
//清除p堆,将h层以上的木块进行归位
void clear_above(int p,int h){
    for(int i=h+1;i<pile[p].size();i++){
        int k=pile[p][i];
        pile[k].push_back(k);
    }
    pile[p].resize(h+1);
}
//把第p堆高度为h及以上的木块全部堆到第p2堆的顶部
void pileon(int p,int h,int p2){
    for(int i=h;i<pile[p].size();i++){
        pile[p2].push_back(pile[p][i]);
    }
    pile[p].resize(h);
}
//打印出所有的木块
void print(){
    for(int i=0;i<n;i++){
        printf("%d:",i);
        for(int j=0;j<pile[i].size();j++){
            printf(" %d",pile[i][j]);
        }
        printf("\n");
    }
}
int main()
{
    cin>>n;
    for(int i=0;i<n;i++)pile[i].push_back(i);
    string s1,s2;
    int a,b;
    while(cin>>s1){
        if(s1 =="quit") break;
        cin>>a>>s2>>b;
        int pa,ha;//a所在的堆和高度
        int pb,hb;//b所在的堆和高度
        find_block(a,pa,ha);
        find_block(b,pb,hb);
        if(pa == pb) continue; //非法指令
        if(s2 == "onto") clear_above(pb,hb);//有onto就要把b上方的木块移掉
        if(s1 == "move") clear_above(pa,ha);
        pileon(pa,ha,pb);
    }
    print();
    return 0;
}