题面
The little fairy has a ribbon with cells and an infinite variety of colors. The first cells of the ribbon have already been colored, where the -th cell is colored with color .
Little fairy will color the remaining cells in order from to . For the -th cell:
- Little fairy first counts the number of distinct colors currently present on the ribbon, denoted as .
- Then she will color the -th cell with color .
What color will the fairy use for the -th cell?
Input
Each test contains multiple test cases. The first line contains the number of test cases (). The description of the test cases follows.
The first line of each test case contains a single integer () — the number of colored cells.
The second line of each test case contains integers () — the colors of the cells.
Output
For each test case, print the color of the last cell.
思路
设初始出现过的颜色集合为 且
对于任意一步,若当前不同颜色数为 则新染色为
若 ,则本次不引入新颜色且之后每步仍染 因而答案为
若 ,则加入新颜色 ,使集合大小变为 即
因此, 单调递增直到首次满足 为止
实现上从 开始循环检查,若不在则插入并 否则输出 \
代码
#include <bits/stdc++.h>
using namespace std;
int main() { int t; cin >> t; while (t --) { int n; cin >> n;
unordered_set<int> c; c.reserve(n * 2 + 10); for (int i = 0; i < n; i ++) { int x; cin >> x; c.insert(x); }
int k = (int)c.size(); while (true) { if (c.count(k)) { cout << k << endl; break; } c.insert(k); k ++; } }}