UVa 127 - "Accordian" Patience

模拟栈,题目本身不难,但条件较多必须认真读题,因为错误理解了"每次都从最左边的纸牌开始操作"而被样例卡了两天,最后又读了两遍题才明白过来,这种水题......哎,唯一值得安慰的是改完后,一遍AC了...水平还是有待提高啊~

代码如下:

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
struct game
{
    char rank[52+2],suit[52+2];
    int n;
} ga[52+2];
void move_ga(int j)      //将空格填满,后边的纸堆依次向前移一个
{
    for(int i=j; i<52; i++)
    {
        if(ga[i+1].n==0)
            break;
        for(int k=0; k<ga[i+1].n; k++)
        {
            ga[i].rank[k]=ga[i+1].rank[k];
            ga[i].suit[k]=ga[i+1].suit[k];
        }
        ga[i].n=ga[i+1].n;
    }
}
void cover_s (int X,int j,char s,char r,int nn)
{
    ga[j-X].suit[nn]=s;
    ga[j-X].rank[nn]=r;
    ga[j].n--;
    ga[j-X].n++;
}
int pile()
{
    int count=52,j,flag;
    char s,r;
    while(1)               //不断循环,直到纸牌不再改变
    {
        flag=0;
        for(j=1; j<count; j++)
        {
            int n,nn,wct=0;
            n=ga[j].n;
            s=ga[j].suit[n-1];
            r=ga[j].rank[n-1];
            if(j-3>=0)
            {
                nn=ga[j-3].n;
                if(s==ga[j-3].suit[nn-1]||r==ga[j-3].rank[nn-1])
                {
                    cover_s(3,j,s,r,nn);
                    wct=flag=1;
                }
            }
            if(wct==0&&j-1>=0)
            {
                nn=ga[j-1].n;
                if(s==ga[j-1].suit[nn-1]||r==ga[j-1].rank[nn-1])
                {
                    cover_s(1,j,s,r,nn);
                    flag=1;
                }
            }
            if(flag==1&&ga[j].n==0)
            {
                move_ga(j);
                --count;
                ga[count].n=0;
            }
            if(flag==1)
                break;
        }
        if(flag==0)                //若纸牌没有改变则跳出循环
            break;
    }
    return count;
}
int main()
{
#ifdef test
    freopen("sample.txt","r",stdin);
#endif
    while(1)
    {
        int count=0;
        scanf("%c",&ga[0].rank[0]);
        if(ga[0].rank[0]=='#')
            break;
        scanf("%c",&ga[0].suit[0]);
        ga[0].n=1;
        ga[52].n=0;
        for(int i=1; i<=51; i++)
        {
            getchar();
            scanf("%c%c",&ga[i].rank[0],&ga[i].suit[0]);
            ga[i].n=1;
        }
        count=pile();
        if(count>1)
            printf("%d piles remaining:",count);
        else
            printf("%d pile remaining:",count);
        for(int i=0; i<count; i++)
            printf(" %d",ga[i].n);
        puts("");
        getchar();
    }
    return 0;
}


你可能感兴趣的:(c)