算法竞赛入门经典之例题 3-4 猜数字游戏的提示(Master-Mind Hints,Uva 340)

题目:实现一个经典“猜数字”游戏。给定答案序列和用户猜的序列,统计有多少数字位置正确(A),有多少数字在两个序列都出现过但位置不对(B)。

输入包含多组数据。每组输入第一行为序列长度n,第二行是答案序列,接下来是若干猜测序列(A,B)。猜测序列全为0时该组数据结束。n = 0时输入结束。

样例输入:

4

1 3 5 5

1 1 2 3

4 3 3 5

6 5 5 1

6 1 3 5

1 3 5 5

0 0 0 0

10

1 2 2 2 4 5 6 6 6 9

1 2 3 4 5 6 7 8 9 1

1 1 2 2 3 3 4 4 5 5

1 2 1 3 1 5 1 6 1 9

1 2 2 5 5 5 6 6 6 7

0 0 0 0 0 0 0 0 0 0

0

样例输出:

 Game 1:

        (1,1)

        (2,0)

        (1,2)

        (1,2)

        (4,0)

Game 2:

        (2,4)

        (3,2)

        (5,0)

        (7,0)

#include <iostream>
using namespace std;
#define maxn 1010

int a[maxn],b[maxn];

int main()
{
	int n, count = 0;
	while(scanf("%d",&n) == 1 && n != 0)
	{
		for(int i = 0; i < n; i++)
			cin >> a[i];
		cout << "Game " << ++count << ":" << endl;
		while(true)
		{
			bool flag = true;
			int num = 0;
			int A = 0, B = 0;
			for(int i = 0; i < n; i++)
			{
				cin >> b[i];
				if(b[i] == 0)
					num++;
				if(num == n)
				{
					flag = false;
					break;
				}	
				if(a[i] == b[i])
					A++;
			}
			if(flag == false)
				break; 
			for(int d = 1; d < 10; d++)			//统计1-9个数字在答案序列和猜测序列中各出现的次数,取min(c1,c2)值(好好想,为什么),再减去已经配对的数字组合A,就能得到B了 
			{
				int c1 = 0, c2 = 0;
				for(int i = 0; i < n; i++)
				{
					if(a[i] == d)	c1++;
					if(b[i] == d)	c2++;
				}
				if(c1 < c2)
					B += c1;
				else
					B += c2;
			}	
			cout << "\t" << "(" << A << "," << B - A << ")" << endl;
		}
	}
	return 0;
}

    

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值