题解:AtCoder AT_awc0100_b Cooking Contest

【题目来源】

AtCoder:B - Cooking Contest

【题目描述】

Takahashi and Aoki are serving as judges for a cooking contest. In this contest, \(N\) participants each submit one dish, and the two judges assign a score to every dish.

The participants are numbered from \(1\) to \(N\). Let \(A_i\) be the score that Takahashi gives to participant \(i\)'s dish, and \(B_i\) be the score that Aoki gives to participant \(i\)'s dish. Each score is an integer between \(1\) and \(100\), inclusive.

Each participant's final score is determined by the sum of Takahashi's score and Aoki's score, \(A_i + B_i\). The participant with the highest final score wins. It is guaranteed that there is exactly one participant with the highest final score.

Find the participant number of the winner.

高橋和青木正在担任一场烹饪比赛的评委。在这场比赛中,\(N\) 名参赛者每人提交一道菜,两位评委为每道菜打分。

参赛者编号为 \(1\)\(N\)。设 \(A_i\) 为高橋给参赛者 \(i\) 的菜的分数,\(B_i\) 为青木给参赛者 \(i\) 的菜的分数。每个分数都是 \(1\)\(100\) 之间的整数(包含 \(1\)\(100\))。

每位参赛者的最终分数由高橋的分数与青木的分数之和 \(A_i + B_i\) 决定。最终分数最高的参赛者获胜。保证恰好有一名参赛者的最终分数最高。

求获胜者的参赛者编号。

【输入】

\(N\)
\(A_1\) \(B_1\)
\(A_2\) \(B_2\)
\(\vdots\)
\(A_N\) \(B_N\)

The first line contains an integer \(N\), representing the number of participants. Of the following \(N\) lines, the \(i\)-th line contains Takahashi's score \(A_i\) and Aoki's score \(B_i\) for participant \(i\), separated by a space.

【输出】

Print the participant number with the highest final score on a single line.

【输入样例】

3
50 60
80 70
40 90

【输出样例】

2

【核心思想】

  1. 问题分析:给定 \(N\) 名参赛者,每人有两个分数 \(A_i\)\(B_i\),最终分数为 \(A_i + B_i\)。保证恰好有一名最高分参赛者,求其编号。这是一个线性扫描找最大值问题,关键在于遍历过程中维护当前最高总分及其对应编号。

  2. 算法选择

    • 直接模拟(线性扫描):遍历所有参赛者,计算总分 \(A_i + B_i\),实时更新最大值和对应编号
    • 单变量维护:用 maxn 记录当前最高总分,maxi 记录对应编号,无需存储所有数据
  3. 关键步骤

    • 初始化:读入 \(N\)maxn = 0, maxi = 0
    • 遍历比较\(i\)\(1\)\(N\)):
      • 读入 \(A_i, B_i\)
      • maxn < A_i + B_i,则 maxn = A_i + B_i, maxi = i
    • 输出 maxi
  4. 时间/空间复杂度

    • 时间复杂度:\(O(N)\),线性遍历 \(N\) 名参赛者
    • 空间复杂度:\(O(1)\),仅使用常数变量
  5. 线性扫描找最大值的核心思想

    • 在线处理:不存储所有参赛者的数据,而是读入一个处理一个,用常数空间维护当前最优解
    • 严格大于保证唯一性:题目保证恰好一名最高分,使用 < 而非 <= 更新,确保遇到相同分数时保留先出现的(本题中相同情况不会发生)
    • 即时更新策略:每读入一组数据立即比较更新,避免后续二次遍历,体现贪心思想的最优子结构
    • 适用于"找唯一最大值及其位置"的基础问题

【算法标签】

模拟

【代码详解】

#include <bits/stdc++.h>
using namespace std;

int n, maxn, maxi;                 // n: 参赛者数量; maxn: 当前最高总分; maxi: 当前最高总分对应的参赛者编号

int main()
{
    cin >> n;                      // 读取参赛者数量 N

    for (int i = 1; i <= n; i++)  // 循环遍历每一位参赛者
    {
        int a, b;                  // a: 高桥给参赛者 i 的分数; b: 青木给参赛者 i 的分数
        cin >> a >> b;             // 读取两位评委的打分

        if (maxn < a + b)          // 如果当前参赛者的总分超过当前最高总分
        {
            maxn = a + b;          // 更新最高总分
            maxi = i;              // 更新最高总分对应的参赛者编号
        }
    }

    cout << maxi << endl;          // 输出获胜者的参赛者编号

    return 0;
}

【运行结果】

3
50 60
80 70
40 90
2
posted @ 2026-08-07 17:09  团爸讲算法  阅读(4)  评论(0)    收藏  举报