枚举算法的优化(二) POJ1013称硬币

枚举算法

我们先来看题目

POJ1013称硬币
问题描述
有12枚硬币。其中有11枚真币和1枚假币。假币和真币重量不同,但不知道假币比真币轻还是重。现在,用一架天平称了这些币三次,告诉你称的结果,请你找出假币并且确定假币是轻是重,数据保证一定能找出来
输入样例
ABCD EFGH even
ABCI EFJK up
ABIJ EFGH even
输出样例
K it is light.

问题分析

程序代码

#include<iostream>
#include<cstring>
using namespace std;
char Left[3][7];
char Right[3][7];
char result[3][7];
bool IsFake(char c, bool light); //light为真表示假设硬币为轻,反之为重
int main() {
	int t;
	cin >> t;
	while (t--)
	{
		cout << "No." << t << endl;
		for (int i = 0; i < 3; i++)
			cin >> Left[i] >> Right[i] >> result[i];
		for (char c = 'A'; c <= 'L'; c++)
		{
			if (IsFake(c, true))
				cout << c << "it is light" << endl;
			else if (IsFake(c, false))
				cout << c << "it is weight" << endl;
		}
	}
	system("pause");
	return 0;
}

bool IsFake(char c, bool light)
{
	for (int i = 0; i < 3; i++)
	{
		char *pleft, *pright; //指向天平两侧字符串
		if (light){
			pleft = Left[i];
			pright = Right[i];
		}
		else {
			pleft = Right[i];
			pright = Left[i];
		}
		switch (result[i][0]){//天平右边的情况
			case 'u':
				if (strchr(pright, c) == NULL)//函数原型char *strchr(const char *str, int c)
					return false;
				break;

			case 'e':
				if (strchr(pleft, c) || strchr(pright, c))
					return false;
				break;

			case 'd':
				if (strchr(pleft, c) == NULL)
					return false;
				break;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43699716/article/details/93477426