UVa-127 "Accordian" Patience(栈+模拟链表)

来源:互联网 发布:matlab 矩阵保存excel 编辑:程序博客网 时间:2024/06/06 11:07

题目大意:给出52张牌(52堆),从左到右,如果一张牌和他左边第一张牌或左边第三张牌匹配(匹配的含义是点数或者花色相同),就把它移动到左边第一张或第三张上面,如果同时匹配则移动到左边第三张上面,这张牌可以一直移动一直到无法匹配为止。如果有一堆牌移空了,则把后面的堆往前挪填补这个位置。最后输出牌的堆数和每堆牌的牌数。

#include<iostream>#include<cstring>#include<stack>using namespace std;struct Card{      char s[3];  };  const int N = 52;    Card card[N];   bool match(Card a,Card b) {      return a.s[0] == b.s[0] || a.s[1] == b.s[1];  }int main(){        while(1){    stack<Card>  st[N];          cin >> card[0].s;          if(card[0].s[0] == '#')              break;          st[0].push(card[0]);          for(int i = 1;i < N; i++) {              cin >> card[i].s;              st[i].push(card[i]);          }          int n = N;for(int i = 0; i<n; i++){    if(i >= 0 && st[i].empty()) {                  for(int j = i;j < n - 1; j++) {                     st[j] = st[j+1];  //把后面的栈往前挪一个位置,填补空掉的栈                }                  n--;                 //出现一个空栈则堆数减1                i--;                 //因为执行完if语句后,i++,下面的i-=4和i-=2同理                continue;              }              if(i - 3 >= 0 && match(st[i].top(),st[i-3].top())) {                  st[i-3].push(st[i].top());                  st[i].pop();                  i -= 4;                  continue;              }              if(i - 1 >= 0 && match(st[i].top(),st[i-1].top())) {                  st[i-1].push(st[i].top());                  st[i].pop();                  i -= 2;                  continue;              }}if(n==1){    printf("1 pile remaining: 52\n");}else{    printf("%d piles remaining: ", n);    for(int i = 0; i<n; i++){printf("%d", st[i].size());if(i!=n-1) printf(" ");else printf("\n");    }}    }return 0;}


原创粉丝点击