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

把52张牌从左到右排好,每张牌形成一个牌堆。当某张牌与它左边的那张牌或者左边第三张牌花色相同或点数相同,就把这张牌移动到那张牌系上面。移动后,在观察是否可以发生其他移动,移动卡牌的原则是,越左边的越先移动,如果能移动,优先移动三张的,牌堆有空隙的时候,立刻填补空隙。

要点:

  • 注意一下没牌把空隙补充,有牌的时候一张一张移动,而不是一堆一堆,因此牌的点数和花色不能直接覆盖,应该用stack存,因为涉及数组的移动,因此建议用链表,这里用数组链表来做。
#include
using namespace std;

struct Card {
	stack<string> s;
	int left, right;
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	int cnt = 0;
	string s;

	while (cin >> s) {
		if (s == "#") break;
		cnt = 0;
		Card c[53];
		c[cnt].left = cnt - 1;
		c[cnt].right = cnt + 1;
		c[cnt].s.push(s);
		cnt++;

		while (cin >> s) {
			c[cnt].left = cnt - 1;
			c[cnt].right = cnt + 1;
			c[cnt].s.push(s);
			cnt++;
			if (cnt == 52) break;
		}
		bool vis[52] = { 0 };
		for (int i = 0; i < cnt; i++) {
			if (vis[i]) continue;
			int index = i;
			for (int j = 0; j < 3; j++) {
				index = c[index].left;
				if (index == -1) break;
			}
			//三张牌
			if (index != -1) {
				if (c[index].s.top()[0] == c[i].s.top()[0] ||
					c[index].s.top()[1] == c[i].s.top()[1]) {
					c[index].s.push(c[i].s.top());
					c[i].s.pop();
					if (c[i].s.empty()) {
						c[c[i].left].right = c[i].right;
						if (c[i].right != 52)
							c[c[i].right].left = c[i].left;
						vis[i] = true;
					}
					i = -1;
					continue;
				}
			}
			index = c[i].left;
			//一张牌
			if (index != -1) {
				if (c[index].s.top()[0] == c[i].s.top()[0] ||
					c[index].s.top()[1] == c[i].s.top()[1]){
					c[index].s.push(c[i].s.top());
					c[i].s.pop();
					if (c[i].s.empty()) {
						c[c[i].left].right = c[i].right;
						if (c[i].right != 52)
							c[c[i].right].left = c[i].left;
						vis[i] = true;
					}
					i = -1;
					continue;
				}
			}
		}
		vector<int> ans;
		for (int i = 0; i < cnt; i++) {
			if (!vis[i])
				ans.push_back(i);
		}
		int size = ans.size();
		cout << size << " pile" << (size > 1 ? "s" : "") << " remaining:";
		for (auto& num : ans) {
			cout << " " << c[num].s.size();
		}
		cout << endl;
	}
}


你可能感兴趣的:(UVA,栈)