猜数字

L1-056 猜数字 (20 分)
 

一群人坐在一起,每人猜一个 100 以内的数,谁的数字最接近大家平均数的一半就赢。本题就要求你找出其中的赢家。

输入格式:

输入在第一行给出一个正整数N(≤)。随后 N 行,每行给出一个玩家的名字(由不超过8个英文字母组成的字符串)和其猜的正整数(≤ 100)。

输出格式:

在一行中顺序输出:大家平均数的一半(只输出整数部分)、赢家的名字,其间以空格分隔。题目保证赢家是唯一的。

输入样例:

7
Bob 35
Amy 28
James 98
Alice 11
Jack 45
Smith 33
Chris 62

输出样例:

22 Amy







 1 #include <iostream>
 2 #include <cmath>
 3 #include <map>
 4 using namespace std;
 5 int main(){
 6     int N;
 7     cin >> N;
 8     map<string, int> Map;
 9     int sum = 0;
10     int K = N;
11     while(N--){
12         string s1; 
13         int T;
14         cin >> s1 >> T;
15         sum += T;
16         Map[s1] = T;
17     }
18     int AVG = sum / K;
19     AVG /= 2;
20     int Step = 101;
21     string s2;
22     for(map<string, int>::iterator it = Map.begin(); it != Map.end(); it++){
23         int temp = abs(it->second - AVG);
24         if(temp < Step){
25             Step = temp;
26             s2 = it->first;
27         }
28     }
29     cout << AVG << ' ' << s2 << endl; 
30     return 0;
31 }
原文地址:https://www.cnblogs.com/AGoodDay/p/10606121.html