UVA 127 - "Accordian" Patience
Algorithm:
1. Gradually input the card
2. Insert the card at its temperarory 'final' place
3. Start from the next position of the inserted card, rearrange the position of the piles of the cards
The idea is implemented as follow:
1 #include <iostream> 2 #include <list> 3 #include <vector> 4 using namespace std; 5 6 struct Pair{ 7 char num; 8 char suit; 9 }; 10 11 typedef vector< list<Pair> > Piles; 12 typedef int Position; 13 14 bool match(Pair c1, Pair c2){ 15 return c1.num == c2.num || c1.suit == c2.suit; 16 } 17 18 Position insert(Pair card, Piles& p, Position pos){ 19 Position left = pos-1, left3rd = pos-3; 20 21 if(left3rd >= 0 && match(p[left3rd].front(), card)) 22 return insert(card, p, left3rd); 23 else if(left >= 0 && match(p[left].front(), card)) 24 return insert(card, p, left); 25 else 26 return pos; 27 } 28 29 void rearrange(Piles& p, Position pos){ 30 if( pos == p.size() ) 31 return; 32 Pair card = p[pos].front(); 33 Position new_pos = insert(card, p, pos); 34 if( new_pos != pos ){ 35 p[new_pos].push_front(card); 36 p[pos].pop_front(); 37 if( p[pos].empty() ){ 38 Piles::iterator it = p.begin(); 39 p.erase( it+pos ); 40 } 41 } 42 rearrange(p, new_pos+1); 43 } 44 45 int main(int argc, char *argv[]){ 46 47 Piles p; 48 Pair card; 49 50 while(cin >> card.num && card.num != '#'){ 51 if(card.num == '\n') 52 continue; 53 else 54 cin >> card.suit; 55 // Find the 'temperary final' position of the card 56 Position pos = insert(card, p, p.size()); 57 if (pos == p.size()){ 58 list<Pair> temp; 59 temp.push_front(card); 60 p.push_back(temp); 61 } 62 else 63 p[pos].push_front(card); 64 65 // Rearrange the cards 66 rearrange(p, pos+1); 67 68 } 69 cout << p.size() << " piles remaining: "; 70 for(int i = 0; i < p.size() ; i++){ 71 cout << p[i].size() << " "; 72 } 73 cout << endl; 74 return 0; 75 76 }
这里的东西都是自娱自乐的.我只是抱着构思算法的心态去做UVA的题.
我所有的code都不可能AC的.因为我就没想着让它能AC.

浙公网安备 33010602011771号