2009年2月7日 星期六

Q127: "Accordian" Patience

// Run time: 1.020
#include <stdio.h>
#define NUM 52
typedef struct {
char suit;
char rank;
} Card;
Card card[NUM];
int index[NUM]; // 指出每個陣列現在指到哪
int check[NUM][NUM];
void Accordian();

int main()
{
int i;
while (true)
{
scanf("%c", &card[0].rank);
if (card[0].rank == '#')
break;
else
{
scanf("%c ", &card[0].suit);
for ( i = 1; i < NUM-1; i++)
{
scanf("%c%c ", &card[i].rank, &card[i].suit);
}
scanf("%c%c", &card[NUM-1].rank, &card[NUM-1].suit);

for ( i = 0; i < NUM; i++)
check[i][0] = i;
for ( i = 0; i < NUM; i++)
index[i] = 1;
}

Accordian();
scanf("\n");
}
return 0;
}

void Accordian()
{
int max = NUM;
int i, j, k;
for (; ;)
{
int count = 0;
for ( i = 1; i < max; i++)
{
if ( i-3 >= 0 &&
(card[check[i][index[i]-1]].rank == card[check[i-3][index[i-3]-1]].rank ||
card[check[i][index[i]-1]].suit == card[check[i-3][index[i-3]-1]].suit))
{
check[i-3][index[i-3]] = check[i][index[i]-1]; // push in
index[i]--;
index[i-3]++;


if (!index[i]) // if it's empty after moving
{
for ( j = i; j < max-1; j++)
index[j] = index[j+1];
index[max-1] = 0;

for ( j = i; j < max-1; j++)
{
for ( k = 0; k < index[j]; k++)
check[j][k] = check[j+1][k];
}
max--;
}
i = 0;
count++;

}
else
if ( i-1 >= 0 &&
(card[check[i][index[i]-1]].rank == card[check[i-1][index[i-1]-1]].rank ||
card[check[i][index[i]-1]].suit == card[check[i-1][index[i-1]-1]].suit))
{
check[i-1][index[i-1]] = check[i][index[i]-1];
index[i]--;
index[i-1]++;


if (!index[i]) // if it's empty after moving
{
for ( j = i; j < max-1; j++)
index[j] = index[j+1];
index[max-1] = 0;

for ( j = i; j < max-1; j++)
{
for ( k = 0; k < index[j]; k++)
check[j][k] = check[j+1][k];
}
max--;
}
i = 0;
count++;
}

}
if (!count)
{
if (max == 1)
printf("1 pile remaining: 52");
else
{
printf("%d piles remaining:", max);
for ( i = 0; i < max; i++)
printf(" %d", index[i]);
}
printf("\n");
return;


}
}

}

沒有留言: