UVa 127 - "Accordian" Patience POJ 1214 链表题解
UVa和POJ都有这道题。
不同的是UVa要求区分单复数,而POJ不要求。
使用STL做会比較简单,这里纯粹使用指针做了,很麻烦的指针操作,一不小心就错。
调试起来还是很费力的
本题理解起来也是挺费力的,要搞清楚怎样模拟也不easy啊,读题要非常细致。
纯指针的操作挺快的吧。
只是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; }