zoukankan      html  css  js  c++  java
  • [C++]猜数字游戏的提示(Master-Mind Hints,UVa340)

    [本博文非博主原创,思路与题目均摘自 刘汝佳《算法竞赛与入门经典(第2版)》]

    Question

    例题3-4 猜数字游戏的提示(Master-Mind Hints,UVa340) 

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

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

    Example Input

    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

    Example Output

    Game 1:
      (1,1)
      (2,0)
      (1,2)
      (1,2)
      (4,0)
    Game 2:
      (2,4)
      (3,2)
      (5,0)
      (7,0)

    Code 

    /*
    	例3-4 猜数字游戏的提示(Master-Mind Hints,UVa340) 
    */
    #include<iostream>
    using namespace std;
    
    const int maxn = 1010; 
    
    int main(){
    	int a[maxn],b[maxn];
    	int A,B,n,cases = 0;
    	while(scanf("%d", &n) == 1 && n){//n=0,则:结束 
    		printf("Game %d:
    ", ++cases);
    		for(int i=0;i<n;i++){
    			scanf("%d", &a[i]); //输入答案序列 
    		}
    		while(true){
    			B = 0;
    			A = 0;//位置一一匹配成功对:A归零
    			for(int j=0;j<n;j++){
    				scanf("%d", &b[j]);
    				if(a[j] == b[j])
    					A++;
    			}
    			if(b[0] == 0)//默认猜测序列的首元素为0,则为全0,结束猜测 
    				break;
    			int c1,c2;
    			for(int d=1;d<9;d++){//对于1-9,答案序列与猜测序列分别统计对应数字有多少个				
    				c1 = 0;
    				c2 = 0;
    				for(int j=0;j<n;j++){
    					if(a[j] == d)
    						c1++;
    					if(b[j] == d)
    						c2++;
    				} 
    				B += c1<c2?c1:c2;//对同一数字,答案序列的次数与猜测序列出现数字的次数,两序列中同一数字出现的次数最少值为m,则说明:
    				//	各数字在两序列中一一对应的对数不超过m,其中m包含了两部分:
    				//		1.一一对应的对数;	2.位置不匹配的对数 
    			}
    			printf("(%d,%d)
    ", A, B - A);	
    		}
    	}
    	return 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	 
    */
    

      

  • 相关阅读:
    [记录] web icon 字体
    ruby sass Encoding::CompatibilityError for changes
    [CSS][转载]内层div的margin-top影响外层div
    PHP 有关上传图片时返回HTTP 500错误
    APK downloader
    阿里云CentOS7.2卸载CDH5.12
    CentOS7查询最近修改的文件
    service cloudera-scm-server restart报错 Unable to retrieve remote parcel repository manifest
    CDH安装报错 Monitor-HostMonitor throttling_logger ERROR ntpq: ntpq -np: not synchronized to any server
    CDH5.12安装检查Inspector failed on the following hosts...
  • 原文地址:https://www.cnblogs.com/johnnyzen/p/9096888.html
Copyright © 2011-2022 走看看