POJ1013称硬币 枚举法

题目:POJ1013称硬币

题目描述:有12枚硬币。其中有11枚真币和1枚假币。假币和真币重量不同,但不知道假币比真币轻还是重。现在,用一架天平称了这些币三次,告诉你称的结果,请你找出假币并且确定假币是轻是重(数据保证一定能找出来)。

●输入样例 注意:天平左右的硬币数总是相等的,even,up,down指的是天平右侧的状态
2
ABCD EFGH even
ABCI EFJK up
ABIJ EFGH even
ABCD IJKL even
ABCE GJKL even
ABCF AGKL up

●输出样例
K is the counterfeit coin and it is light.
F is the counterfeit coin and it is heavy.

题解:
枚举法,枚举第i枚硬币为轻、重两种情况,如果符合三次称量即输出。

程序(这是郭炜老师的程序)

#include 
#include 
#include 

using namespace std;

#define light false
#define heavy true

vector<string> L;//天平左
vector<string> R;//天平右
vector<string> S;//天平状态

bool isFalse(char c, bool b)
{
	string Left, Right, State;
	for (int i = 0; i < 3; i++) {
		if (b == light) {
			Left = L[i];
			Right = R[i];
		}
		else{
			Left = R[i];
			Right = L[i];
		}
		State = S[i];
		switch (State[0]) {
			case 'u':
				if (Left.find(c) != string::npos)
					return false;
				break;
			case 'e':
				if (Left.find(c) != string::npos || Right.find(c) != string::npos)
					return false;
				break;
			case 'd':
				if (Right.find(c) != string::npos)
					return false;
				break;
		}
	}
	return true;
}

int main()
{
	int N;
	cin >> N;
	for (int i = 0; i < N; i++) {
		string s1, s2, s3;
		for (int j = 0; j < 3; j++) {
			cin >> s1 >> s2 >> s3;
			L.push_back(s1);
			R.push_back(s2);
			S.push_back(s3);
		}
		for (char c = 'A'; c <= 'L'; c++) {
			if (isFalse(c, light)) {
				cout << c << " is the counterfeit coin and it is light." << endl;
				break;
			}
			if (isFalse(c, heavy)) {
				cout << c << " is the counterfeit coin and it is heavy." << endl;
				break;
			}
		}

		L.clear();
		R.clear();
		S.clear();

	}
	system("pause");
	return 0;
}

你可能感兴趣的:(POJ1013称硬币,枚举法,算法设计)