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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值