《算法竞赛入门经典2ndEdition》 例题3-4 猜数字游戏的提示(Master-Mind Hints, Uva340)

看了好久还是没看懂题,看了这位大哥(http://www.cppblog.com/rakerichard/archive/2011/04/09/143775.html)翻译的再去看了下题才理解了题意,那个strong weak 串第一开始没读懂,结果只是按照样例弄的,现在终于AC了。 英语不好是硬伤。。。。

#include <cstdio>
#include <cstring>
#include <algorithm>
const int maxn = 1000;
int num[maxn + 20], book[10], booknum[10], guess[maxn + 20], bookguess[10];
using namespace std;
int main()
{
  //freopen("New Text Document.txt","r",stdin);
  //freopen("Output.txt","w",stdout);
  int n, game = 0;
  while(scanf("%d", &n) == 1 && n)
  {
    printf("Game %d:\n",++game);
    memset(book, 0, sizeof(book));
    for(int i = 1; i <= n; i++)
    {
      scanf("%d", &num[i]);
      book[num[i]]++;
    }
    int x;
    while(scanf("%d", &x) && x)
    {
      memset(bookguess, 0, sizeof(bookguess));
      for(int i = 1; i<= 9; i++) booknum[i] = book[i];
      int right = 0, appear = 0;
      guess[1] = x;
      bookguess[x]++;
      if(guess[1] == num[1]) 
      {
        right++;
        booknum[x]--;
        bookguess[x]--;
      }
      for(int i = 2; i <= n; i++)
      {
        scanf("%d", &guess[i]);
        bookguess[guess[i]]++;
        if(guess[i] == num[i]) 
        {
          right++;
          booknum[guess[i]]--;
          bookguess[guess[i]]--;
        }
      }
      for(int i = 1; i <= 9; i++)
      {
        if(bookguess[i] && booknum[i]) appear += min(bookguess[i], booknum[i]);
      }
      printf("    (%d,%d)\n",right,appear);
    }
    for(int i = 2; i <= n; i++)
      scanf("%d", &x);
  }
  //getchar();getchar();
  return 0;
} 

底下是刘汝佳标程
https://github.com/aoapc-book/aoapc-bac2nd/blob/master/ch3/UVa340.cpp

// UVa340 Master-Mind Hints
// Rujia Liu
#include<stdio.h>
#define maxn 1000 + 10

int main() {
  int n, a[maxn], b[maxn];
  int kase = 0;
  while(scanf("%d", &n) == 1 && n) { // n=0时输入结束
    printf("Game %d:\n", ++kase);
    for(int i = 0; i < n; i++) scanf("%d", &a[i]);
    for(;;) {
      int A = 0, B = 0;
      for(int i = 0; i < n; i++) {
        scanf("%d", &b[i]);
        if(a[i] == b[i]) A++;
      }
      if(b[0] == 0) break; // 正常的猜测序列不会有0,所以只判断第一个数是否为0即可
      for(int d = 1; d <= 9; d++) {
        int c1 = 0, c2 = 0; // 统计数字d在答案序列和猜测序列中各出现多少次
        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;
      }
      printf("    (%d,%d)\n", A, B-A);
    }
  }
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值