zoukankan      html  css  js  c++  java
  • 猜数字游戏的提示(Master-Mind Hints, UVa 340)

    实现一个经典"猜数字"游戏。

    给定答案序列和用户猜的序列,统计有多少数字位置正确 (A),有多少数字在两个序列都出现过但位置不对(B)。

    输入包含多组数据。每组输入第一行为序列长度n,第二行是答案序列,接下来是若干猜测序列。猜测序列全0时该组数据结束。n=0时输入结束。

    样例输入:

    4

    1 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的部分。

    #include<cstdio>
    #define maxn 1010 
    using namespace std;
    int a[maxn],b[maxn];
    int main(){
        int count=0;int n;
        while(scanf("%d",&n)==1&&n){//n=0时输入结束 
            printf("Game %d:
    ", ++count);
            for(int i=0;i<n;i++) scanf("%d",&a[i]);
            while(1){
                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)
    ", A, B-A);
            }
        }
    return 0;
    }
  • 相关阅读:
    JS数组方法汇总 array
    jQuery性能优化
    js禁止保存网页的一些代码
    XML LINQ简介
    一个滑动条的DIV+CSS+JS实例
    JS的正则表达式
    jQuery中$.ajax的实现
    MSSQL 2005删除所有表的语句[转]
    Jquery Toggle with Images
    SQLIte default date CURRENT_TIMESTAMP
  • 原文地址:https://www.cnblogs.com/LOW-ctfer/p/10363308.html
Copyright © 2011-2022 走看看