C3L-UVa340-Master-Mind Hints

平台:

UVa Online Judge

題號:

340 - Master-Mind Hints

題目連結:

https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=5&page=show_problem&problem=276

題目說明:

实现一个经典"猜数字"游戏。给定答案序列和用户猜的序列,统计有多少数字位置正确(A),有多少数字在两个序列都出现过但位置不对(B)。输入包含多组数据。每组输入第一行为序列长度n,第二行是答案序列,接下来是若干猜测序列。猜测序列全0时该组数据结束。n=0时输入结束。

範例輸入:

41
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)

解題方法:

直接统计可得A,为了求B,对于每个数字(1~9),统计二者出现的次数c1和c2,则min(c1,c2)就是该数字对B的贡献。最后要减去A的部分。

 
 

程式碼:

 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 const int MAXN = 1005;
 5 
 6 int min(int a, int b) {
 7     return a < b ? a : b;
 8 }
 9 
10 void getCnt(int num[], int cnt[],int n) {
11     for (int i = 0; i < n; i++) {
12         cnt[num[i]]++;
13     }
14 }
15 
16 void myScanf(int num[], int n) {
17     for (int i = 0; i < n; i++) {
18         scanf("%d", num + i);
19     }
20 }
21 
22 bool is_allZero(int num[], int n) {
23     for (int i = 0; i < n; i++) {
24         if (num[i] != 0) {
25             return false;
26         }
27     }
28     return true;
29 }
30 
31 int get_weak(int cnt1[], int cnt2[]) {
32     int sum = 0;
33     for (int i = 0; i < 10; i++) {
34         sum += min(cnt1[i], cnt2[i]);
35     }
36     return sum;
37 }
38 
39 int get_strong(int num1[], int num2[],int n) {
40     int sum = 0;
41     for (int i = 0; i < n; i++) {
42         if (num1[i] == num2[i]) {
43             sum++;
44         }
45     }
46     return sum;
47 }
48 
49 int main() {
50     int n = 0;
51     int cnt = 0;
52     while (scanf("%d",&n) == 1 && n) {
53         printf("Game %d:\n", ++cnt);
54         int secret[MAXN] = { 0 };
55         memset(secret, 0, sizeof(secret));
56         //输入答案
57         myScanf(secret, n);
58         int sCnt[10] = { 0 };
59         getCnt(secret, sCnt,n);
60         while (true) {
61             int guess[MAXN] = { 0 };
62             memset(guess, 0, sizeof(guess));
63             myScanf(guess, n);
64             //如果输入全是0,则退出
65             if (is_allZero(guess,n)) {
66                 break;
67             }
68             int gCnt[10] = { 0 };
69             getCnt(guess, gCnt,n);
70             int strong = 0, weak = 0;
71             strong = get_strong(secret, guess,n);
72             weak = get_weak(sCnt, gCnt);
73             printf("    (%d,%d)\n", strong, weak - strong);
74         }
75     }
76     return 0;
77 }

猜你喜欢

转载自www.cnblogs.com/lemonforce/p/13200198.html
今日推荐