UVa 101 The Blocks Problem

题意:给出从左到右放置的n块木块(从0开始编号),再给出四种操作,再给出相应的操作,输出操作结束后每一堆木块的情况。

学习的紫书,因为每一堆的木块数是在发生变化的,所以用vector。 然后就是模拟几种操作

学习了这个& 在这个函数里面,find_block(inta,int &p,int&h)

紫书上写的注释是“找出木块a所在的pile和height,以引用的形式返回调用者”

最开始不明白= =然后写了一个小的程序试验了一下

 1 #include<iostream>  

 2 #include<cstdio>  

 3 #include<cstring>  

 4 #include<algorithm>  

 5 using namespace std;

 6 

 7 void f(int &h)

 8 {

 9     h=1;

10     h=2;

11     h=555;    

12 }

13 

14 int main()

15 {

16     int ha;

17     f(ha);

18     printf("ha=%d\n",ha);    

19 }

UVa 101 The Blocks Problem

 

应该是最后p的值变为了多少,就将这个值返回到那个相应的实参的值

 1 #include<iostream>  

 2 #include<cstdio>  

 3 #include<cstring>  

 4 #include<algorithm>  

 5 #include<vector>

 6 using namespace std;

 7 

 8 const int maxn=30;

 9 int n;

10 vector<int> pile[maxn];

11 

12 void find_block(int a,int &p,int &h)//找出木块a在哪一堆,及其所在的那一堆的高度 

13 {

14     for(p=0;p<n;p++)

15      for(h=0;h<pile[p].size();h++)

16      if(pile[p][h]==a) return;    

17 }

18 

19 void clear_above(int p,int h)//将第p队高度为h以上的放回原位置 

20 {

21     for(int i=h+1;i<pile[p].size();i++)

22     {

23         int b=pile[p][i];

24         pile[b].push_back(b);//第b块的原位置在第b堆 

25     }

26     pile[p].resize(h+1);    

27 }

28 

29 void pile_onto(int p,int h,int p2)//将第p堆高度为h及其上方的木块整体移到p2堆上 

30 {

31     for(int i=h;i<pile[p].size();i++)

32     pile[p2].push_back(pile[p][i]);

33     pile[p].resize(h);

34 } 

35 

36 void print() //输出每一堆的情况 

37 {

38     for(int i=0;i<n;i++)

39     {

40         printf("%d:",i);

41         for(int j=0;j<pile[i].size();j++)

42         printf(" %d",pile[i][j]);

43         printf("\n"); 

44     }

45 }

46 

47 int main()

48 {

49     int a,b;

50     cin>>n;

51     string s1,s2;

52     for(int i=0;i<n;i++)

53     pile[i].push_back(i);

54     while(cin>>s1>>a>>s2>>b)

55     {

56         int ha,hb,pa,pb;

57         find_block(a,pa,ha);

58         find_block(b,pb,hb);        

59         if(pa==pb) continue;

60         if(s2=="onto") clear_above(pb,hb);//当语句中含有onto时,都是要将b堆上面的放置回原位置的 

61         if(s1=="move") clear_above(pa,ha);//当语句中含有move时,都是要将a堆上面的放置回原位置的

62         pile_onto(pa,ha,pb);

63     }

64     print();

65     return 0;

66 }
View Code

 

你可能感兴趣的:(block)