1. 程式人生 > >猜數字遊戲的提示

猜數字遊戲的提示

image images 思路 mes cst () font 題目 blog

題目來自劉汝佳編著的《算法競賽入門經典(第二版)》

題目描述:
技術分享

技術分享

技術分享

技術分享

技術分享

技術分享

我的代碼:

#include<iostream>
#include<cstring>
using namespace std;
int main() {
    int answer[100];
    int copy[100];
    int enter[100];
    int n, a, b;
    int count = 0;
    n = 1;
    while (n != 0)
    {
        cin >> n;
    
        for
(int i = 0; i < n; i++) cin >> answer[i]; cout << "Game " << ++count << endl; while (1) { a = b = 0; for (int i = 0; i < n; i++) copy[i] = answer[i]; for (int i = 0
; i < n; i++) cin >> enter[i]; if (enter[0] == 0) break; for (int i = 0; i < n; i++) { if (copy[i] == enter[i]) { a++; enter[i] = copy[i] = 0; } }
for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (copy[i] == enter[j] && i != j && enter[j] != 0) { b++; enter[j] = copy[i] = 0; } } } cout << "\t" << "(" << a << "," << b << ")" << endl; } } return 0; }

答案的代碼:

#include<stdio.h>
#define maxn 1010

int main() {
    int n, a[maxn], b[maxn];
    int kase = 0;
    while (scanf("%d", &n) == 1 && n) {
        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;
            for (int d = 1; d <= 9; d++) {
                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;
            }
            printf("    (%d, %d)\n", A, B - A);
        }
    }
    return 0;
}

這次博主有點懶。。。題目就截圖貼上去了,博主做完本題之後感覺。。。自己的算法不是很精妙,答案的思路很清奇,有沒有大神能貢獻自己的算法呢??╮(╯▽╰)╭

猜數字遊戲的提示