Daily practice 2023.12.11——Guess the number [PTA]

Question link:L1-056 Guess the number 

Topic requirements:

A group of people sit together and each guess a number within 100. Whoever's number is closest to half of the average number wins. This question requires you to find the winner.

Input format:

The input is given as a positive integer N (≤104) on the first line. Then there are N lines, each line gives a player's name (a string consisting of no more than 8 English letters) and the positive integer guessed (≤ 100).

Output format:

Output sequentially on one line: half of everyone's average (only the integer part is output), and the name of the winner, separated by spaces. The question guarantees a unique winner.

Input example:

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

Output sample:

22 Amy

Idea:

1. According to the question requirements, first define an array s to store the string, that is, the name, and an array x to store the reported number.

2. Loop through and add the reported numbers to sum, find the average and store it in t.

3. Loop through again to find out the difference between each number and half of the average, and find the number with the smallest difference.

4. Loop through again to find the subscript of the minimum difference, and finally print out half of the average value and the name of the minimum difference.

Code:

#include <bits/stdc++.h>

using namespace std;

#define N 10000
int main()
{
    int n;
    cin >> n;
    string s[N];
    int x[N];
    int sum = 0;
    for(int i = 0; i < n; i ++)
    {
        cin >> s[i] >> x[i];
        sum += x[i];
        
    }
    int t = sum / n / 2;
    int z;
    int m = N;
    for(int i = 0; i < n; i ++)
    {
        if(x[i] - t > 0)
            z = x[i] - t;
        else
            z = t - x[i];
        m = min(z, m);
    }
    int idx;
    for(int i = 0; i < n; i ++)
    {
        if(x[i] - t == m || t - x[i] == m)
            idx = i;
    }
    cout << t << " " << s[idx] << endl;
    return 0;
}

Test Results:

Supongo que te gusta

Origin blog.csdn.net/m0_63168877/article/details/134908949
Recomendado
Clasificación