刚看题的时候没有一点头绪,后来看懂题了然后不会用语言实现,真是失败,后来在网上找了个ACb0y的代码开始研究,个人认为他那个if_can_close_up函数有点问题,下面是我改完后的代码 #include <iostream> #include <cstring> using namespace std ; struct node { char suit ; char rank ; } ; struct myStack { node val[60] ; int top ; myStack() : top(0) {}} ; myStack data[60] ; bool visit[60] ; void init( char s[][100] ) { int count = 0 ; for( int i = 0 ; i < 2 ; i++ ) { int len = strlen( s[i] ) ; for( int j = 0 ; j < len ; j += 3 ) { data[count].top = 0 ; data[count].val[data[count].top].rank = s[i][j] ; data[count].val[data[count].top].suit = s[i][j+1] ; data[count].top = 1 ; count++ ; } } memset( visit , false , sizeof( visit ) ) ; return ; } bool can_move( node a , node b ) { if( a.rank == b.rank || a.suit == b.suit ) return true ; return false ; } int getMatchPos( int pos ) { if( visit[pos] ) return -1 ; int fpos = -1 ; int spos = -1 ; int count = 0 ; for( int i = pos - 1 ; i >= 0 ; i-- ) { if( !visit[i] ) { count++ ; if( count == 1 ) spos = i ; if( count == 3 ) { fpos = i ; } if( count > 3 ) break ; } } if( fpos == -1 && spos == -1 ) return -1 ; else if( fpos != -1 && can_move( data[pos].val[data[pos].top - 1] , data[fpos].val[data[fpos].top - 1] ) ) return fpos ; else if( spos != -1 && can_move( data[pos].val[data[pos].top -1] , data[spos].val[data[spos].top - 1] ) ) return spos ; else return -1 ; } int main() { char str[2][100] ; memset( str , 0 , sizeof( str ) ) ; int icase = 0 ; while( 1 ) { gets( str[0] ) ; if( str[0][0] == '#' ) break ; gets( str[1] ) ; init( str ) ; int flag = 0 ; int i = 0 ; while( i < 52 ) { int matchPos = getMatchPos( i ) ; if( matchPos == -1 ) i++ ; else { data[matchPos].val[data[matchPos].top].rank = data[i].val[data[i].top - 1].rank ; data[matchPos].val[data[matchPos].top].suit = data[i].val[data[i].top - 1].suit ; data[matchPos].top++ ; data[i].top-- ; if( data[i].top == 0 ) visit[i] = true ; i = matchPos ; } } int count = 0 ; for( int i = 0 ; i < 52 ; i++ ) if( !visit[i] ) count++ ; if( count == 1 ) cout << "1 pile remaining: 52" << endl ; else { cout << count << " piles remaining:" ; for( int i = 0 ; i < 52 ; i++ ) if( !visit[i] ) cout << " " << data[i].top ; cout << endl ; } } return 0 ; }