天天看點

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

           

繼續閱讀