首页 > 代码库 > UVa 127 - "Accordian" Patience POJ 1214 链表题解

UVa 127 - "Accordian" Patience POJ 1214 链表题解

UVa和POJ都有这道题。

不同的是UVa要求区分单复数,而POJ不要求。

使用STL做会比较简单,这里纯粹使用指针做了,非常麻烦的指针操作,一不小心就错。调试起来还是非常费力的

本题理解起来也是挺费力的,要搞清楚如何模拟也不容易啊,读题要很仔细。

纯指针的操作挺快的吧。不过POJ 0ms,而UVa就0.2左右了。

三相链表:

1 只要有叠起来的牌,那么就使用一个down指针指向下面的牌就可以了。

2 使用双向链表,可以方便前后遍历。

3 记得有了更新牌之后,又要重新开始检查是否需要更新牌,这是模拟的需要,不然或WA的。

#include <stdio.h>

struct Node
{
	int size;
	Node *pre, *post;
	Node *down;
	char a, b;
	Node () : pre(NULL), post(NULL), down(NULL), size(1) {}
};

//insert n to m position
inline void insertNode(Node *&m, Node *&n)
{
	n->post = m->post;
	n->pre = m->pre;
	if (m->post) m->post->pre = n;//小心断链
	if (m->pre) m->pre->post = n;//小心断链
}

inline void takeoutNode(Node *&n)
{
	if (n->down)
	{
		Node *down = n->down;
		insertNode(n, down);
		return;
	}
	if (n->pre) n->pre->post = n->post;
	if (n->post) n->post->pre = n->pre;
}

inline void inStackNode(Node *&m, Node *&n)
{
	n->size = m->size+1;
	insertNode(m, n);
	n->down = m;
}

inline bool checkMovable(Node *n, Node *m)
{
	return n->a == m->a || n->b == m->b;
}

inline void pre3(Node *&n)
{
	if (n->pre) n = n->pre;
	if (n->pre) n = n->pre;
	if (n->pre) n = n->pre;
}

inline void pre1(Node *&n)
{
	if (n->pre) n = n->pre;
}

inline void deleteNodes(Node *&n)
{
	while (n)
	{
		Node *p = n->post;
		while (n)
		{
			Node *d = n->down;
			delete n; n = NULL;
			n = d;
		}		
		n = p;
	}
}

int main()
{
	Node *head = new Node; //Dummy head
	while (true)
	{
		Node *it = new Node;
		it->a = getchar();
		if (it->a == '#') break;
		it->b = getchar();
		getchar();

		head->post = it;//initialize chain
		it->pre = head;

		for (int i = 1; i < 52; i++)
		{
			Node *p = new Node;
			p->a = getchar();
			p->b = getchar();
			getchar();
			it->post = p;
			p->pre = it;
			it = p;
		}
		bool checkMove = true;
		while (checkMove)
		{
			checkMove = false;
			it = head->post;
			while (it)
			{
				Node *post = it->post;
				Node *p = it;
				pre3(p);
				if (p && p != head && checkMovable(p, it))
				{
					checkMove = true;				
					takeoutNode(it);
					inStackNode(p, it);//调用参数不要乱了
					break;
				}
				p = it;
				pre1(p);
				if (p && p != head && checkMovable(p, it))
				{
					checkMove = true;
					takeoutNode(it);
					inStackNode(p, it);
					break;//题意,理解
				}
				it = post;
			}//while (it)
		}//while (checkMove && piles > 1)
		it = head->post;
		int piles = 0;
		while (it)
		{
			piles++;
			it = it->post;
		}
		if (piles == 1) printf("%d pile remaining:", piles);
		else printf("%d piles remaining:", piles);
		it = head->post;
		while (it)
		{
			printf(" %d", it->size);
			it = it->post;
		}
		putchar('\n');
		deleteNodes(head->post);
	}//while (true)
	delete head;
	return 0;
}