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 <iostream>
#include <string>
#include <vector>

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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章