UVa 340 - Master-Mind Hints

题目链接:点击打开链接


解题思路:

设数字位置正确的有a个,数字相同但位置不同的有b个。

假设答案序列中有5个1,输入的序列中有4个1,其中我们知道数字位置正确的有1个,那么对于1来说,数字相同但位置不同的有多少个呢?

答案是3个,想一想。

关键在于这个思想,其中对于1来说,b = min(5,4)-a = min(5,4) - 1 = 5。

那么因为输入序列是1到9的数字,我们只需要统计1到9里面,对于答案序列和猜测序列中,1出现的最少次数,2出现的最少次数,3出现的最少次数,……。因为统计的时候一定包含数字位置正确的个数,所以最后的结果再减去数字位置正确的个数即可。


代码:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <ctype.h>
using namespace std;

int n;

int main()
{
    int cnt = 0;
    while(scanf("%d", &n) == 1 && n)
    {
        int *a = new int[n+1];
        int *b = new int[n+1];

        printf("Game %d:\n", ++cnt);

        for(int i = 0; i < n; i++)
            scanf("%d", &a[i]);
        while(1)
        {
            int c1, c2;
            c1 = c2 = 0;
            int ans1, ans2;
            ans1 = ans2 = 0;
            for(int i = 0; i < n; i++)
            {
                scanf("%d", &b[i]);
                if(b[i] == a[i])
                    ans1++;
            }
            if(b[0] == 0)
                break;

            for(int i = 1; i <= 9; i++)
            {
                c1 = c2 = 0;
                for(int j = 0; j < n; j++)
                {
                    if(a[j] == i)
                        c1++;
                    if(b[j] == i)
                        c2++;
                }
                ans2 += min(c1, c2);
            }
            printf("    (%d,%d)\n", ans1, ans2-ans1);
        }
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值