AOAPC I: Beginning Algorithm Contests (Rujia Liu) :: Volume 1. Elementary Problem Solving :: Sorting/Searching
Description
很经典的 MasterMind 游戏,游戏规则已经被人熟知,只是游戏原型比较少人了解。
游戏规则就是,由一个人出题,一个人解密。
密码由 N 位 1~9 的数字组成。
解密者不断提出猜测,出题人每次根据解密者的猜测给予提示。
提示内容为,猜测中有多少个数字完全正确,有多少个数字仅仅是位置不对。
输入密码和多次猜测,输出每次猜测对应的提示。
Type
Sorting/Searching
Analysis
先把猜测中,完全正确的数字找出来,这是比较容易实现的。
只要对于每个位置,检查密码和猜测中该位置上的数字是否一致即可。
然后我们将不一致的猜测放入集合中。
再从头检索,对于还没猜出来的数字,查找集合中是否有该数字,
如果有,则说明有一个位置不对的数字。
然后将该数字从集合中删去,继续查找。
直到找完位置,即可AC。
Solution
// UVaOJ 340
// Master-Mind Hints
// by A Code Rabbit
#include <cstdio>
#include <set>
#include <vector>
using namespace std;
const int MAXN = 100000;
int n;
int code[MAXN];
int guess[MAXN];
int main() {
int cnt_case = 0;
while (scanf("%d", &n) && n) {
for (int i = 0; i < n; i++)
scanf("%d", &code[i]);
printf("Game %d:\n", ++cnt_case);
while (1) {
for (int i = 0; i < n; i++)
scanf("%d", &guess[i]);
if (!guess[0]) break;
int strong = 0, weak = 0;
vector<int> que;
multiset<int> ans;
for (int i = 0; i < n; i++) {
if (code[i] != guess[i]) {
que.push_back(code[i]);
ans.insert(guess[i]);
} else {
strong++;
}
}
for (int i = 0; i< que.size(); i++) {
multiset<int>::iterator iter = ans.find(que[i]);
if (iter != ans.end()) {
weak++;
ans.erase(iter);
}
}
printf(" (%d,%d)\n", strong, weak);
}
}
return 0;
}