UVa 127 "Accordian" Patience (纸牌游戏)

很好的一道栈与链表的题目,链表直接用数组实现,代码还算清晰吧,注释具体看代码吧。

#include<iostream>
#include<stdio.h>
#include<stack>
using namespace std;

int nSize;

struct String{
    char face[3];
};
struct Pile{
    stack<String>face;
}arr[100];
int prev[100],next[100];

void DelGap(){//clear the empty gap
    int i,j;
    for(i = 0;i != nSize;i = next[i]){
        if(arr[i].face.empty()){
            next[prev[i]] = next[i];//把当前i的prev的next指向当前i的next
            prev[next[i]] = prev[i];
        }
    }
}
bool Move(){//the operation of move
    int cnt = 1;
    for(int i = next[0];i != nSize;i = next[i],++cnt){
        int last3,last1;
        if(cnt > 2){
        //if present position is equal or above 3,judge to move 3 positions
            last3 = prev[prev[prev[i]]];
            if(arr[i].face.top().face[0] == arr[last3].face.top().face[0]
               ||arr[i].face.top().face[1] == arr[last3].face.top().face[1]){
                arr[last3].face.push(arr[i].face.top());
                arr[i].face.pop();
                return true;
             }
        }
        //else judge to move 1 position
        last1 = prev[i];
        if(arr[i].face.top().face[0] == arr[last1].face.top().face[0]
         ||arr[i].face.top().face[1] == arr[last1].face.top().face[1]){
            arr[last1].face.push(arr[i].face.top());
            arr[i].face.pop();
            return true;
        }
    }
    return false;
}
void Solve(){
    while(Move())
        DelGap();
}
int main()
{
    nSize = 0;
    String temp;
    while(scanf("%s",temp.face) == 1)
    {
        if(temp.face[0] == '#') break;
        while(!arr[nSize].face.empty())
            arr[nSize].face.pop();
        arr[nSize].face.push(temp);
        prev[nSize] = nSize - 1;
        next[nSize] = nSize + 1;
        ++nSize;
        if(nSize == 52){
            Solve();
            int num = 0;
            for(int i = 0;i != nSize;i = next[i])
                ++num;
            if(num == 1) printf("1 pile remaining: ");
            else printf("%d piles remaining: ",num);
            for(int i = 0;i != nSize;i = next[i]){
                if(i) printf(" ");
                printf("%d",arr[i].face.size());
            }
            printf("\n");
            nSize = 0;
        }
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值