公式

D - Greedy Draft 解説 by en_translator


Implementation approach

Initialize the “collection of chosen juice numbers” with an empty set, and inspect the wish list of customer \(1, \dots, N\) in order.

When inspecting the wish list of customer \(i\), perform the following:

  • Execute a loop to inspect each element \(X_{i,j}\) in order. For each inspection:
    • Do nothing if \(X_{i,j}\) is contained in the “collection of the chosen numbers.”
    • Otherwise, determine that customer \(i\) chooses \(X_{i,j}\). Insert \(X_{i,j}\) to the “collection of chosen numbers,” and escape from the loop.
  • If the loop above does not determine customer \(i\)’s choice, determine that customer \(i\) chooses water.

There are several ways to implement the “collection of chosen numbers”:

  • An array such that the \(k\)-th element is \(1\) if \(k\) is chosen, and \(0\) otherwise.
    • To determine if \(x\) is contained, check if the \(x\)-th element is \(1\).
    • To insert \(x\), set the \(x\)-th element to \(1\).
  • An associative array.
    • Most languages provide an associative array type that supports basic operations like insertion and existence check as a standard feature.

Both approaches provide necessary operations.

Sample code (Python 3 and C++)

The following is sample code in Python 3. The associative array used is the “collection of chosen numbers.”

n, m = map(int, input().split())

used = set()
for i in range(n):
	len = int(input())
	x = 0
	draftlist = list(map(int, input().split()))
	for v in draftlist:
		if not (v in used):
			x = v
			used.add(x)
			break
	print(x)

The following is sample code in C++. The associative array issued is the “collection of chosen numbers.”

#include <iostream>
using std::cin;
using std::cout;
#include <vector>
using std::vector;

int main (void) {
	std::cin.tie(nullptr);
	std::ios_base::sync_with_stdio(false);

	int n, m;
	cin >> n >> m;
	
	vector<int> isused(m+1, 0);
	for (int i = 0; i < n; i++) {
		int len;
		cin >> len;

		vector<int> x(len);
		for (int j = 0; j < len; j++) {
			cin >> x[j];
		}

		int ans = 0;
		for (int j = 0; j < len; j++) {
			if (isused[x[j]] == 0) {
				isused[x[j]] = 1;
				ans = x[j];
				break;
			}
		}

		cout << ans << "\n";
	}

	return 0;
}

投稿日時:
最終更新: