题目链接:点击打开链接
解题思路:
设数字位置正确的有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;
}