您的位置:首页 > 产品设计 > UI/UE

POJ 2328 Guessing Game

2011-08-04 13:42 417 查看
题目: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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: