Sicily 1018. A Card Trick【排列组合】

题目链接在此


这道题题意有些难理解,解法倒是不难。

主要是将5张牌做全排列,然后找出符合要求的一种情况即可。


最大的收获是加深了对next_permutaiton函数的理解。

在此题中,我是把每张牌抽象成了一个包含牌数(int value)和花色(char suit)的结构体。

对结构体运用next_permutaiton有两点要特别注意:

(1)要自定义以一个比较函数,两种方法任选一种:

a.在结构体定义中直接重载<或==或>操作符

b.额外写个比较函数(用过std::sort对这个方法不陌生)

(2)遍历所有的全排列情况之前,一定要对结构体数组,按照上面说的这个比较函数做一次排序(用std::sort会比较方便),若使用升序,则后面必须用next_permutaiton,若为降序则必须用prev_permutaiton。否则,会从中间遍历的全排列情况,导致情况缺失。


值得一提的是,在当前数组其中的元素处于任一顺序状态下的时候,

next_permutaiton所遍历的数量+prev_permutaiton所遍历的数量 = 数组中元素的全排列情况数量 + 1


以下是源代码:

#include<iostream>
#include<stdio.h>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;

struct card {
	int value;
	char suit;

	card() {}
	card(int v, char s) : value(v), suit(s){}

	bool operator < (const card& other) const {
		return (value < other.value) || (value == other.value && suit < other.suit);
	}
};

void initialize(card* cards) {
	string tmp;
	for (int i = 0; i < 5; i++) {
		cin >> tmp;
		if (tmp.length() == 2) {
			if (tmp[0] == 'A')
				cards[i].value = 1;
			else if (tmp[0] == 'J')
				cards[i].value = 11;
			else if (tmp[0] == 'Q')
				cards[i].value = 12;
			else if (tmp[0] == 'K')
				cards[i].value = 13;
			else
				cards[i].value = tmp[0] - '0';
		}
		else if (tmp.length() == 3) {
			cards[i].value = 10;
		}
		cards[i].suit = tmp[tmp.length() - 1];
	}
}

void printResult(int counter, card* cards) {
	printf("Problem %d:", counter);

	for (int i = 0; i < 5; i++) {
		printf(" ");
		if (cards[i].value == 1)
			printf("A");
		else if (cards[i].value == 11)
			printf("J");
		else if (cards[i].value == 12)
			printf("Q");
		else if (cards[i].value == 13)
			printf("K");
		else
			printf("%d", cards[i].value);

		printf("%c", cards[i].suit);
	}

	printf("\n");
}

int main() {
	int caseNum;

	cin >> caseNum;
	for (int counter = 1; counter <= caseNum; counter++) {
		card cards[5];
		initialize(cards);
		sort(cards, cards + 5);  //  必须排序!!!

		do {
			if (cards[0].suit != cards[1].suit)
				continue;

			int sum = cards[1].value;
			int minIndex;
			card min(20, 'Z');
			vector<card> toBeCmped;

			for (int k = 2; k < 5; k++)
				if (cards[k] < min) {
					min.value = cards[k].value;
					min.suit = cards[k].suit;
					minIndex = k;
				}

			for (int k = 2; k < 5; k++) {
				if (k != minIndex)
					toBeCmped.push_back(cards[k]);
			}

			if (toBeCmped[0] < toBeCmped[1])
				sum += (minIndex - 1);
			else
				sum += (minIndex - 1) + 3;

			if (sum % 13 == cards[0].value) {
				printResult(counter, cards);
				break;
			}
		} while (next_permutation(cards, cards + 5));
	}

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值