木块问题(Th Blocks Problem,UVa 101)
通过这道题学到了把指令的共同点提取出来,编写函数来减少重复代码,以前我都是按整句话来处理的,学到了。
最近一直在刷UvaOJ,只不过前几章的题太简单,没有往上写博客…
看了答案后默写代码都会出错Orz
1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 #include<algorithm> 5 #include<vector> 6 using namespace std; 7 const int maxn = 30 ; 8 int n ; 9 vector<int> pile[maxn]; 10 11 void found_pile( int a , int &p , int &h) // 以引用形式返回方块a的位置 12 { 13 for( p = 0 ; p < n; p++) 14 for( h = 0 ; h < pile[p].size() ; h++) 15 if( pile[p][h] == a ) 16 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); 25 } 26 pile[p].resize(h+1); 27 return ; 28 } 29 30 void pile_onto( int p , int h , int p2) // 把第p堆高度为h及其上方的木块整体移动到p2堆的顶部 31 { 32 for( int i = h ; i < pile[p].size() ; i++) 33 pile[p2].push_back(pile[p][i]); 34 pile[p].resize(h); 35 return ; 36 } 37 38 void print() 39 { 40 for( int i = 0 ; i < n ; i++) 41 { 42 printf("%d:",i); 43 for( int j = 0 ; j < pile[i].size() ; j++) 44 printf(" %d",pile[i][j]); 45 printf("\n"); 46 } 47 } 48 49 50 int main() 51 { 52 string s1,s2; 53 int a , b ; 54 cin >> n ; 55 for( int i = 0 ; i < n ; i++) 56 pile[i].push_back(i); 57 while( cin >> s1 >> a >> s2 >> b ) 58 { 59 int pa , pb , ha , hb; 60 found_pile(a,pa,ha); 61 found_pile(b,pb,hb); 62 if( pa == pb ) 63 continue ; 64 if( s2 == "onto" ) 65 clear_above(pb,hb); 66 if( s1 == "move" ) 67 clear_above(pa,ha); 68 pile_onto(pa,ha,pb); 69 } 70 print(); 71 return 0 ; 72 }
浙公网安备 33010602011771号