公式

C - Colorful Beans 解説 by en_translator


Suppose that you chose a bean of color \(c\). Then, the minimum possible deliciousness is the minimum deliciousness among the beans of color \(c\).

Thus, this problem requires to find for each color the minimum deliciousness of a bean of that color, and choose the maximum value among them.

One can obtain the correct answer by scanning all the \(N\) beans for each color, but there are at most \(N\) distinct colors, so implementing this naively costs \(O(N^{2})\) time, which exceeds the execution time limit.

In this problem, you can use an associative array (std::map or std::unordered_map in C++, or dict or deafaultdict in Python) to manage the minimum deliciousness of each color, so that the program runs in \(O(N\log{N})\) or expected \(O(N)\) time. Specifically, iterate the given beans; if the associative array contains the index of the color of the current bean, update the minimum deliciousness; otherwise, add a new index of the color and let the minimum value the deliciousness of that bean. This way, you can obtain the minimum deliciousness of each color in the end.

For more details, please refer to the sample code.

What is an associative array? An associative array is in a sense an extension of an ordinary array. While an array takes indices $0,1,2,\ldots$, which are consecutive integers greater than or equal to $0$, an associative array accepts an arbitrary types or values.
On initialization, it does not contain an index. Insertion or deletion of an index, updating the value associated to an index, and obtaining the distinct number of indices can be done fast, in constant or logarithmic time.

Sample code (C++):

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

int main() {
  int n;
  cin >> n;

  map<int, int> minimum_taste; // Minimum deliciousness of each color
  for (int i = 0; i < n; ++i) {
    int a, c;
    cin >> a >> c;
    if (minimum_taste.contains(c)) {
      // Update the minimum value if color `c` already exists
      minimum_taste[c] = min(minimum_taste[c], a);
    } else {
      // Add new color
      minimum_taste[c] = a;
    }
  }

  int ans = -1;
  // Scan all the existing colors
  for (auto [c, val] : minimum_taste){
    ans = max(ans, val);
  }

  cout << ans << endl;
}

投稿日時:
最終更新: