这道题目略坑,如果用模拟来做的话,其实很简单,一开始想的是模拟之后觉得集合更简答,但是忽略了一点是,用集合来做的话,集合是无序的,但是题目中得输入顺序是有序的。而且用模拟的时间复杂度为O(n^2).
1 #include <stdio.h>
2 #include <string.h>
3 #define MAXN 1024
4
5 int left, chance;
6 int win, lose;
7 void guess(char ch);
8
9 char p[MAXN] = {0}, g[MAXN] = {0};
10 int main() {
11
12 int r = 0;
13
14 while (scanf("%d%s%s",&r, p, g) == 3 && r != -1) {
15
16 printf("Round %d\n", r);
17 win = lose = 0;
18 left = strlen(p);
19 chance = 7;
20 for (int i = 0; g[i]; i++) {
21
22 guess(g[i]);
23
24 if (win || lose) break;
25
26 }
27
28 if (win) printf("You win.\n");
29 else if(lose) printf("You lose.\n");
30 else printf("You chickened out.\n");
31
32 }
33 return 0;
34 }
35
36
37 void guess(char ch) {
38
39 int finded = 0;
40 for (int i = 0; p[i]; i++) {
41
42 if (ch == p[i]) {
43 p[i] = ' ';
44 left--;
45 finded = 1;
46
47 }
48
49 }
50
51 if (!finded) --chance;
52 if (!chance) lose = 1;
53 if (!left) win = 1;
54
55 }
by sixleaves