POJ 2328 Guessing Game

本文详细解析了一款猜数字游戏的算法逻辑,包括如何通过提问缩小范围直至找到正确答案,同时讨论了玩家可能说谎的情况,并提供了相应的代码实现。重点介绍了通过输入回答判断是否诚实的方法,以及实现这一过程的C++代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   题目:http://poj.org/problem?id=2328

   题目大意:猜数字游戏,一个人选定一个1-10的数字,另一个人猜,高了说too high,低了说too low。猜中了说right on。因为这个人可能说谎,要求你通过猜测过程判断是否说谎。

    分析:其实相当于有一个low=0,high = 11。然后不断的压缩范围的一个过程,正确的是二分查找法,最后猜中的数字应该落在【low,high】之间。否则说明对方撒谎。

    代码如下:

#include <stdio.h>
#include <string>
#include <iostream>

using namespace std;

#define ONLINE
#define max(a,b) (a)>(b)?(a):(b)
#define min(a,b) (a)<(b)?(a):(b)

void online()
{
#ifdef ONLINE
#else
	freopen("2328.in", "r", stdin);
	freopen("2328.out", "w", stdout);
#endif
}

const char * HIGH = "too high";
const char * LOW = "too low";
const char * RIGHT = "right on";

int g;
char answer[10];
int l, h;

int main()
{
	online();

	l = 0; h =11;
	bool flag = true;
	while (scanf("%d\n", &g) && g != 0)
	{
		cin.getline(answer, 10);
		//scanf("%s", answer);

		if (strcmp(answer,RIGHT) == 0)
		{
			if (g > l && g < h)
			{
				flag = true;
			}
			else
				flag = false;

			if (flag)
			{
				printf("Stan may be honest\n");
			}
			else
				printf("Stan is dishonest\n");

			l = 0; h = 11;
		}
		if (strcmp(answer, HIGH) == 0)
		{
			h = min(g, h);
		}
		else if (strcmp(answer, LOW) == 0)
		{
			l = max(g, l);
		}
	}

	return 0;
}
   运行结果如下:

2328Accepted220K0MSC++1003B2011-08-04 13:36:56


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值