Watson gives to Sherlock a bag of numbers [1, 2, 3 ... N] and then he removes K numbers A1, A2 ... AK from the bag. He now asks Sherlock to find the P'th smallest number in the bag.
Input
First line contains T, the number of test cases. Each test case consists of N, K and P followed by K integers in next line denoting the array A.
Output
For each test case, print P'th smallest number in the bag. If no such number exists output -1.
Constraints
1 ≤ T ≤ 10
20% testdata: 1 ≤ N ≤ 10^3
20% testdata: 1 ≤ N ≤ 10^5
60% testdata: 1 ≤ N ≤ 10^9
0 ≤ K ≤ min(N, 10^5)
1 ≤ P ≤ N
Note: Large input files. Use scanf instead of cin.
SAMPLE INPUT
2
4 1 2
1
5 2 4
1 3
SAMPLE OUTPUT
3
-1
Explanation
Test case 1:
Remaining numbers are [2, 3, 4]. 3 is the 2nd smallest remaining numbers.
Test case 2:
Remaining numbers are [2, 4, 5]. 4th smallest remaining number doesn't exist.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to parse the problem: Given N (max numbers 1..N), K removed numbers (distinct presumably), and P (1-indexed order statistic among remaining numbers). Find the P-th smallest number that is still present. If P > number of remaining numbers (i.e., P > N - K), output -1. But note: K can be up to min(N, 1e5), N up to 1e9, so cannot store all numbers.
We need to compute the P-th smallest among {1..N} \ A, where A is set of removed numbers. Equivalent to find the smallest number x such that count of numbers <= x not in A is >= P. Then we need to output that number if exists; else -1.
But careful: We need exactly P-th smallest, not just the first x. Alternatively, we can binary search on x from 1 to N, compute f(x) = number of numbers in [1, x] that are present (i.e., x - count_removed_in_[1, x]). Then the P-th smallest is the smallest x such that f(x) >= P. However, note that x itself might be removed; if x is removed, f(x) may not count x, so the P-th smallest might be some number that is not present? But actually, the P-th smallest among the present numbers must be a present number. The condition f(x) >= P does not guarantee x is present. To get the exact number, we could find the minimal x with f(x) >= P, but if x is removed, then the actual P-th smallest is the next present number after x? Wait: Let's analyze. f(x) counts present numbers ≤ x. If f(x) >= P, it means the P-th smallest present number is ≤ x. But it could be that x is not present, but there is a present number < x that is the P-th. But if we take the smallest x such that f(x) >= P, then if x is present, it will be the P-th smallest? Not necessarily: Suppose we have numbers 1,2,3,4,5; removed: {2,4}. Present: [1,3,5]. P=2. f(1)=1, f(2)=1 (since 2 removed), f(3)=2. So smallest x with f(x)>=2 is x=3, which is present, and indeed it's the 2nd smallest. Good.
Suppose P=2, present: [1,4,5] (removed 2,3). f(1)=1, f(2)=1, f(3)=1, f(4)=2. Smallest x with f(x)>=2 is x=4, present, 2nd smallest is 4. Good.
Suppose P=2, present: [2,3,4] (removed 1). f(1)=0, f(2)=1, f(3)=2. Smallest x with f>=2 is 3, present, yes.
Suppose P=1, present: [2,3] (removed 1). f(1)=0, f(2)=1. Smallest x with f>=1 is 2, present, good.
Thus it seems the smallest x such that f(x) >= P is always a present number because if x is removed, then f(x) = f(x-1). So if f(x) >= P but x is removed, then f(x-1) = f(x) >= P, so x-1 would also satisfy, contradicting minimality. So minimal x with f(x) >= P must be present. So we can binary search for x.
Thus the problem reduces to: Given sorted list of removed numbers (we can sort A, K up to 1e5), for a given x, compute how many removed numbers are ≤ x. Then f(x) = x - count_removed(≤ x). We need to check f(x) >= P.
Binary search range: low = 1, high = N. But if total present numbers N - K < P, then answer is -1. So we should check that first: if P > N - K, output -1. This handles the sample case 2.
Otherwise, we binary search. Since N up to 1e9, log2(1e9) ~ 30, fine.
Complexities: For each test case, we need to sort A (if not guaranteed sorted? Input says K integers, not necessarily sorted, we should sort). Then for each query (binary search step), we need count of removed numbers <= x, which we can compute using binary search on the sorted array (upper_bound). That's O(log K) per step, total O(log N * log K). Or we can compute directly by scanning? K up to 1e5, but binary search steps ~30, so O(30 log K) is fine.
But T up to 10, total is fine.
Potential pitfalls: The removed numbers may contain duplicates? Probably not; but we can treat duplicates as same, but constraints maybe distinct. If duplicates, it might not affect count (we should count each removal only once, but if duplicates, they'd be invalid because K distinct numbers are removed, but maybe they ensure distinct? Usually yes). But we can just sort and then for counting <= x, use upper_bound that returns index of first > x, so duplicates counted correctly.
Edge Cases: P could be 1; N huge; K=0; then answer is P (since numbers 1..N all present). Check: f(x) = x >= P; smallest x is P, present. Good.
If P = N - K (the maximum), answer is the largest present number. Binary search works.
If N = 0? Not possible since N >= 1.
Now, we need to read input quickly: Use scanf. Output using printf.
Implementation steps:
For each test case:
read N, K, P.
read K integers into list A.
sort A.
if P > N - K: print -1.
else:
low = 1, high = N, ans = 0.
while low <= high:
mid = low + (high - low)/2.
cnt_removed = number of elements in A <= mid. Use binary search: idx = upper_bound(A.begin(), A.end(), mid) - A.begin(); cnt = idx.
present = mid - cnt.
if present >= P:
ans = mid; high = mid - 1.
else:
low = mid + 1.
print ans.
Now, about constraints: K can be 0. Then A empty list. Sorting empty fine. For cnt_removed, if A empty, upper_bound returns 0. present = mid. Binary search works.
Now, we need to ensure no overflow: mid up to 1e9, fine.
Time complexity: Sorting O(K log K) per test. T up to 10, K up to 1e5, so sorting 10*1e5 log 1e5 ~ 1.7e7 operations, okay.
Memory: store A (size K) per test.
Edge Cases: N up to 1e9, K up to 1e5, but P up to N. P could be very large, but we check if P <= N-K.
Potential optimization: Since K is small relative to N, we could also directly compute answer without binary search by iterating through removed numbers and adjusting a pointer. For each removed number, we can consider that the present numbers are the numbers from 1 to N excluding the removed. The P-th smallest present number can be found by considering that the order statistics shift. Another approach: if we sort removed numbers, then we can find the P-th present by scanning: we have blocks of consecutive present numbers. For each interval between removed numbers, the number of present numbers in that interval is length of interval. So we can accumulate until we reach P. That might be more efficient (O(K) after sorting) than binary search (O(log N * log K)). But K is up to 1e5, so O(K) is also fine, and we don't need binary search per step. However, we need to handle the edges: before first removed, between removed, after last removed. This approach could be done directly:
Let sorted removed = R (size K). Then present numbers are:
From 1 to R[0]-1 (if R[0] > 1). Count1 = R[0]-1.
For i from 0 to K-2: between R[i] and R[i+1], present numbers are from R[i]+1 to R[i+1]-1, count = R[i+1] - R[i] - 1.
After last removed: from R[K-1]+1 to N, count = N - R[K-1].
Then we can iterate over these segments, accumulate counts. When accumulated count >= P, answer = start_of_segment + (P - prev_count - 1). And we break. If after all segments we haven't reached P, answer = -1 (but we already checked P <= N-K, so it should be found). This approach avoids binary search and any per-step log. Complexity O(K) after sorting. However, note that K can be 0, then segment is just 1..N, answer = P. If K is large (1e5), O(K) is fine.
But we need to handle the case where there are duplicates? Should not be. However, this approach relies on distinct removed numbers. If duplicates, they'd mess up counts; but we could deduplicate after sorting.
Given the constraints and simplicity, both methods are okay. I'll probably go with binary search because it's straightforward and easier to code without handling many edge cases. However, binary search requires counting removed <= x using binary search, which is O(log K) per iteration. With log N about 30 and T up to 10, that's at most 300 binary searches on array of size up to 1e5, each binary search O(log K) ~ 17, total ~ 5100 operations, trivial. Sorting O(K log K) dominates. So I'll implement binary search.
But one nuance: Since N can be as high as 1e9, but K only up to 1e5, the removed set is relatively sparse. Binary search may do more steps but that's okay.
We must be careful: P can be up to N (1e9), but we check condition.
Edge Cases: If K = N, then N-K =0, only P=1? Actually P ≥1, but if P > 0 then answer -1. That's fine.
Now, ensure we read input correctly: The format: First line T. Then each test case: line with N K P, then next line containing K integers. If K=0, then there might be no line? The problem says "followed by K integers in next line denoting the array A." So if K=0, there will be an empty line? Usually in programming problems, if K=0, the next line may be empty or may not exist; but to be safe, we can read the next line after reading N K P, and if K>0 then parse K integers, else ignore that line (or simply not read). But using scanf, we can just loop K times reading integers regardless; if K=0, we won't read any. However, we need to skip the newline after reading N K P. Usually, after reading the line with N K P, we are at the end of line. Then we want to read K integers. If K=0, there might be no numbers, but there might be a newline. scanf with format "%d" will skip whitespace, so if we try to read K integers, it will just skip the whitespace and attempt to read an integer, but there may be no integer (the next token might be the next test case's N). So we need to be careful: When K=0, we should not attempt to read any integers. So we'll only read if K>0.
Better: after reading N,K,P, we then read exactly K integers using a loop, using scanf("%d", &val). That will consume whitespace and read the numbers from the input. If K=0, loop does nothing, and we proceed. That's safe because there may be no numbers, and we won't attempt to read. But we need to ensure that the input does not have an extra line with nothing; that's fine, because scanf skipping whitespace will ignore empty lines and continue to next token. However, if there is an empty line with no numbers, it's just whitespace, so scanf will skip it and look for the next integer token. But that next integer token may belong to the next test case, causing a read error. Actually, if K=0, then after the line containing N K P, the next token in the input might be the next test case's N (if there is no extra line). So if we try to read K numbers (0 numbers), we don't read anything. The input pointer remains just after the newline of the N K P line. Then we proceed to the next test case reading N, K, P. That's fine because we haven't consumed any token. However, if the problem's input includes an empty line after each test case (like a blank line), that empty line contains newline characters, which are whitespace. When we go to read the next test case's first integer, scanf will skip that whitespace. So it's fine. So we can safely read only if K>0.
Thus we can implement:
int T;
scanf("%d", &T);
while(T--) {
int N, K;
long long P; // P can be up to 1e9, fits in int, but we may need long long for intermediate? Not really, but N up to 1e9, so P could be up to 1e9, fits in 32-bit signed? 1e9 < 2^31-1, so int okay. However, to avoid overflow when computing present = mid - cnt, mid and cnt are up to 1e9 and 1e5, safe in int. But we might use long long for consistency.
scanf("%d %d %lld", &N, &K, &P);
vector A(K);
for(int i=0;i<K;i++) {
scanf("%d", &A[i]);
}
sort(A.begin(), A.end());
long long total_present = N - K; // N up to 1e9, K up to 1e5, fits in int, but N-K may be up to 1e9, fits in 32-bit signed? 1e9 fits, but if N=1e9, K=0, N-K=1e9, still within 32-bit signed (max 2.147e9). So int is fine.
if(P > total_present) {
printf("-1\n");
continue;
}
// binary search
int lo = 1, hi = N;
int ans = N; // placeholder
while(lo <= hi) {
int mid = lo + (hi - lo)/2;
// count removed <= mid
int cnt_removed = upper_bound(A.begin(), A.end(), mid) - A.begin();
long long present = mid - cnt_removed;
if(present >= P) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
printf("%d\n", ans);
}
But we need to be careful: ans must be present number; however, it's possible that ans is not present? As argued earlier, minimal x with f(x) >= P must be present. But let's prove: Suppose ans is minimal such that f(ans) >= P but ans is removed. Then f(ans) = f(ans-1) because ans is removed. So f(ans-1) = f(ans) >= P, so ans-1 also satisfies, contradicting minimality. So ans is present. Good.
Now check for large values: N up to 1e9, mid up to 1e9, but cnt_removed <= 1e5, so present <= 1e9, fits in 32-bit signed. But to avoid overflow in case of larger N? Actually N up to 1e9, safe. So int works.
But P is declared as long long? In scanf we used %lld, but if we use int for P we need %d. P is ≤ N ≤ 1e9, int is fine. But maybe they intend P to be up to 10^9, which is within int range for typical 32-bit, but some compilers have int as 32-bit, max 2.147e9, so okay. I'll just use long long to be safe, but consistent format specifier. But then we compare present (int) with P (long long). That's fine after promotion.
Simplify: use long long for N, K, P? Actually N up to 1e9 fits int, but for arithmetic we might use long long to avoid overflow if we did something like mid - cnt, mid is int, cnt int, difference int; safe. So fine.
Now, consider K up to 1e5, storing vector A(K). That's fine.
Now, a potential issue: The input numbers A could be unsorted, but we sort.
Now, check with sample input: T=2. Test case1: N=4,K=1,P=2; A=[1] -> total_present=3 >=2 -> binary search yields 3. Output 3. Test case2: N=5,K=2,P=4; total_present=3 <4 -> -1. Output -1. Matches.
Now, we should also ensure that the answer exists (P <= N-K). So we can early exit.
Now, about performance: Sorting A O(K log K). For large N but small K, fine.
Now, we need to pay attention to input reading: Use scanf for speed. Since K up to 1e5 and T up to 10, total numbers up to 1e6, so reading with scanf is fine.
Now, one nuance: The problem statement says "0 ≤ K ≤ min(N, 10^5)" So K can be 0, and then there is no line for A? Or there might be a line with nothing. As discussed, reading loop for i=0 to K-1 will skip reading numbers when K=0, which is fine. However, after reading N K P, the input pointer is at the newline. Then if K=0, we skip reading numbers and go to the next test case. But what if the input has an empty line? That's fine. If there is an extra line with spaces, that's also whitespace. When we go to read the next test case's first integer, scanf will skip whitespace. So it's safe.
But there is a subtlety: If K=0, the next token might be the next test case's N. So when we call scanf for the next test case, it will read that number correctly because we didn't consume any numbers. So that's fine.
Now, let's think about potential pitfalls: Upper bound on removed numbers uses binary search. We need to include . In C++, we can use std::upper_bound.
Now, consider memory: We'll allocate vector for each test case, then it goes out of scope.
Now, what about using set? Not needed.
Now, let's test with larger N: N=1e9, K=1e5, P=5e8 (some value). Binary search works; counting removed <= mid using binary search on sorted A each step.
Time: For each test, sorting 1e5 numbers ~ O(1e5 log 1e5) ~ 1.7e6 comparisons. T=10 -> 17e6, fine. Binary search steps ~30, each binary search on vector ~17 comparisons, total 510, negligible.
Thus the solution is efficient.
One more improvement: Instead of binary searching within binary search, we could maintain a pointer while iterating over removed numbers to compute f(mid) in O(1) per binary search step by two-pointer technique, but not necessary.
Now, we must output answer for each test case.
Now, consider an alternative scenario: K might be large relative to N, but K ≤ min(N, 1e5). So if N is small (like 1000), K could be up to 1000. Still fine.
Now, a subtle point: The numbers removed are given as A1...AK. They might not be sorted and may contain numbers > N? But since they are removed from bag [1..N], they should be within 1..N. But it's not explicitly stated, but we can assume they are valid. However, to be safe, we might ignore numbers > N? They would be invalid anyway. But we can trust input.
Now, what about duplicates? If duplicates exist, then our count_removed will count each duplicate, but the actual number of removed numbers might be less than K because duplicates don't remove extra numbers. Then total_present = N - (number of distinct removed). But the problem likely ensures distinct. But if there are duplicates, we could deduplicate. But since constraints say "removes K numbers A1, A2 ... AK from the bag", it implies they are removed one by one; if a duplicate is given, you can't remove the same number twice. So likely they are distinct. So no need to deduplicate.
But to be extra safe, we could deduplicate after sorting: A.erase(unique(A.begin(), A.end()), A.end()); then update K to A.size() and compute total_present = N - K. However, if duplicates exist, then P might be > N - (distinct count) but originally K includes duplicates, so the condition P > N - K might incorrectly think more numbers are removed. For example, N=5, K=2, but A=[3,3] (duplicate). Actually, you can't remove 3 twice, so effective removed count is 1. If we compute total_present = N - K = 3, but actual present count = 4. If P=4, our early check would say -1 but actual answer is 4. So duplicates would break. However, the problem likely does not have duplicates; it's standard. So we won't worry.
Nevertheless, to be absolutely robust, we could deduplicate. The extra cost is O(K). Let's do deduplication just in case. Because the problem statement does not explicitly say that A values are distinct. Usually, they would be. But many problems don't guarantee distinctness. However, they say "removes K numbers A1, A2 ... AK from the bag", meaning he removes them one by one; if there is a duplicate, it would be an invalid operation because the number is no longer in the bag. Usually they ensure they are distinct. But to be safe, I'll add deduplication.
Deduplication after sorting: sort, then unique, erase. Then set K = A.size(). Then compute total_present = N - K. This handles duplicates.
Also need to consider numbers out of range [1,N]? They shouldn't appear, but if they do, they are not in the bag; removing them does nothing. So they shouldn't be in the input; but if they are, they are not actually removed; they are invalid. But we could ignore them: remove numbers not in [1,N] from the set. But again, likely not needed.
But I'll implement deduplication only after sorting.
Now, code.
We'll need to include bits/stdc++.h or iostream, vector, algorithm, cstdio.
Now, outline:
#include <bits/stdc++.h>
using namespace std;
int main() {
int T;
scanf("%d", &T);
while (T--) {
int N, K;
long long P;
scanf("%d %d %lld", &N, &K, &P);
vector A(K);
for (int i = 0; i < K; ++i) {
scanf("%d", &A[i]);
}
sort(A.begin(), A.end());
// deduplicate
A.erase(unique(A.begin(), A.end()), A.end());
K = A.size();
code
long long total_present = N - K;
if (P > total_present) {
printf("-1\n");
continue;
}
int lo = 1, hi = N;
int ans = N;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int cnt_removed = upper_bound(A.begin(), A.end(), mid) - A.begin();
long long present = mid - cnt_removed;
if (present >= P) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
printf("%d\n", ans);
}
return 0;
}
Now, test with sample.
Now, edge case with duplicates: N=5, K=2, A=[3,3], P=4. After deduplication, K=1, total_present=4 >=4. Binary search: A=[3]. Need to find 4th smallest present. Present numbers: 1,2,4,5. 4th smallest is 5. Let's test: binary search: lo=1, hi=5.
mid=3: cnt_removed = 1 (since 3 <=3), present=2 <4 -> lo=4.
mid=4: cnt_removed = 1 (3<=4), present=3 <4 -> lo=5.
mid=5: cnt_removed=1, present=4 >=4 -> ans=5, hi=4? Actually after lo=5, hi=5? Let's step: after lo=4, hi=5: mid=4 => lo=5. Now lo=5, hi=5: mid=5 => present=4>=4 => ans=5, hi=4, exit. ans=5. Good. So dedup works.
Now, if duplicate and also numbers out of range? Not needed.
Now, what about K=0? The vector initially size 0, sorting is fine, dedup does nothing.
Now, one more nuance: The problem says "0 ≤ K ≤ min(N, 10^5)". So K can be equal to N? If K=N, then total_present=0, any P>=1 yields -1.
Now, verify for N large (1e9) and K=0: binary search will find ans = P. That's fine. But binary search might take 30 steps. But we could also directly output P, but not needed.
Now, memory: vector A of size up to 1e5, fine.
Now, might there be an overflow when computing total_present = N - K? N and K are ints, but N up to 1e9, K up to 1e5, difference fits in int. But if N is 1e9 and K=0, total_present=1e9, which fits in int. However, if N is 1e9 and K=0, int is okay. But if N=2e9? Not possible because constraint N ≤ 1e9. So int fine.
But we used long long for P and total_present to compare P > total_present. That's fine.
Now, in binary search, present = mid - cnt_removed. mid and cnt_removed are ints, but we assign to long long present. Not needed but okay.
Now, answer is int.
Now, confirm that the condition present >= P correctly identifies the minimal x. As argued earlier, it's correct.
Now, let's test with a case where the removed numbers are not sorted and there are many. E.g., N=100, K=50 random numbers, P=30. Should work.
Now, what about time: Using std::upper_bound on vector is O(log K). With K up to 1e5, log2(1e5) ~ 17, times 30 = 510 per test, fine.
Now, note: The problem statement: "Large input files. Use scanf instead of cin." So we are using scanf.
Now, we might need to consider the use of 64-bit for P because P can be up to 1e9, which fits in 32-bit, but some compilers treat int as 32-bit, okay. I'll keep long long to be safe.
Now, we need to ensure the output is exactly as required: each test case output on its own line.
Now, check for potential off-by-one: In condition present >= P, we want the smallest x such that count of present numbers up to x is at least P. That's correct for order statistic: the P-th smallest present number y satisfies that count of present numbers ≤ y is exactly P, and for any x < y, count < P.
Now, we might consider the scenario where there are gaps and the binary search might land on a number that is removed but present < P? But we already argued minimal x must be present. Let's double-check with an example where minimal x satisfying f(x) >= P is removed? Let's try to construct: Suppose numbers 1..10, removed: 5,6,7,8,9,10? Actually we want f(x) >= P but x removed, and for any y < x, f(y) < P. Can that happen? Let's try: Present: [1,2,3,4] (removed 5-10). P=4. f(4)=4 (since 4 present, count of present <=4 = 4). f(5)=4 (5 removed). Minimal x with f(x)>=4 is x=4 (present). So not removed.
Suppose P=3. Minimal x is 3 (present). Suppose we remove 1,2,3? Present: [4,5,...]. P=1. f(3)=0, f(4)=1. Minimal x=4 (present). Good.
Is there a case where the minimal x is removed? For x removed, f(x)=f(x-1). So if f(x) >= P, then f(x-1) >= P, so x-1 also qualifies, thus x cannot be minimal. So proof holds. So ans is present.
Thus code is correct.
Now, we could also implement the scanning method: after sorting and dedup, we iterate through the "gaps" and compute cumulative count. That might be more straightforward and avoids binary search inside binary search. Let's examine that method.
Given sorted distinct removed numbers R. Define prev = 0. For each removed r in R (and also after loop for after last), compute count = r - prev - 1 (numbers between prev+1 and r-1). If cumulative + count >= P, then answer = prev + (P - cumulative). That is, starting at prev+1, the (P - cumulative)-th number in this interval. Then break. If not, cumulative += count, set prev = r. After loop, if not found, then it must be after last removed: answer = prev + (P - cumulative). (Since we already checked P <= total_present, it's safe.)
Let's test with earlier examples:
N=10, R=[2,5,7,9,10], prev=0:
r=2: count = 2-0-1=1 (numbers:1). cum=0+1=1 < P=3 -> cum=1, prev=2.
r=5: count =5-2-1=2 (3,4). cum=1+2=3 >=3, then answer = prev + (P - cum_before) = 2 + (3-1)=4? Actually cum_before = cumulative before adding this count = 1. So answer = prev+1 + (P - cum_before -1)? Let's be careful: In interval (prev, r) i.e., numbers from prev+1 to r-1, there are count numbers. We need the (P - cum_before)-th number in this interval, where cum_before is cumulative before this interval. So the index = prev + (P - cum_before). Because the first number is prev+1, second is prev+2, etc. So if P - cum_before = d (1-indexed), the number is prev + d. For the above: cum_before=1, P=3, d=2, prev=2, so answer = 4. Correct.
After loop: if still not found, answer = prev + (P - cum_before). That would be after last removed.
Test with earlier duplicate case: N=5, R=[3], P=4. prev=0, r=3: count=3-0-1=2 (1,2). cum=2 <4. prev=3, cum=2. After loop, answer = prev + (P - cum) = 3 + (4-2)=5. Good.
Test with K=0: R empty, skip loop, cum=0, prev=0, answer = 0 + P = P. Good.
Test with P exactly at boundary: N=10, R=[4,7], P=4. prev=0, r=4: count=3 (1,2,3) cum=3 <4 -> prev=4, cum=3. r=7: count=7-4-1=2 (5,6). cum_before=3, P=4 => d=1, answer = prev + 1 = 4+1=5? Wait, that yields 5, but present numbers: [1,2,3,5,6,8,9,10] Actually after removing 4 and 7, present: 1,2,3,5,6,8,9,10. The 4th smallest is 5. So answer=5, correct.
Check after last: if P=7, total_present=8. cum after processing all removed: after r=7, cum = 3+2=5, prev=7. Then after loop: numbers from 8 to 10: count = N - prev = 10-7=3. cum_before=5, P=7 => d=2, answer = prev + 2 = 7+2=9? Actually the numbers after prev: 8,9,10. 2nd number is 9. And the 7th smallest overall: let's list sorted: 1,2,3,5,6,8,9,10. 7th is 9. Yes.
Thus scanning method works and is O(K) after sorting.
Which method to choose? Both fine. The scanning method might be slightly faster because it avoids binary search inside binary search, but the difference is negligible. However, scanning method has to handle multiple cases and careful indexing. But it's straightforward.
Given the constraints and that binary search is simple and less error-prone, I'll stick with binary search.
But note: The binary search method uses O(log N * log K). With N up to 1e9, that's fine. However, for some test cases where N is huge and K is moderate, both are okay.
One potential issue: The binary search may require 64-bit for mid if we use int? N up to 1e9, int fits. So fine.
Now, consider also that the answer may be -1 only if P > N - K. We've done that.
Now, just implement as described.
Edge Cases to test manually:
N=1e9, K=1e5, P=1e9-1e5? Actually total_present = N-K. If P equals that, answer should be the largest present number, which is N unless N is removed? Since we removed K numbers, the largest present could be N if N is not removed, but could be less if N is among removed. For example, if N is removed, the largest present is N-1 maybe. So binary search will find it.
Let's simulate: N=10, K=2, removed=[9,10], P=8 (N-K=8). Present: 1..8. Answer should be 8. Binary search: lo=1, hi=10. f(8)=8 - cnt_removed(<=8) =8-0? Wait removed are 9,10, so cnt_removed(<=8)=0, present=8 >=8, ans=8? But we need minimal x with present>=8: f(7)=7<8, f(8)=8 => ans=8, present. Good.
Now, if removed includes N, and P = N-K, answer = something else. Eg, N=10, removed=[10], K=1, total_present=9, P=9. Present: 1..9. Answer 9. f(9)=9-0=9 => ans=9. Good.
Now, if removed includes some intermediate numbers, answer might be less than P? For example, N=10, removed=[1,2], P=1. Present: 3..10, 1st smallest = 3. f(3) = 3 - cnt_removed(<=3) =3-2=1 => ans=3. Good.
Now, consider P=1 and removed includes 1. Answer = 2. f(2) = 2 - cnt_removed(<=2). If 1 removed, cnt_removed(<=2) includes 1 maybe 1? Yes, cnt_removed(<=2)=1 (if 1 removed, and 2 not removed). present=1 => ans=2. Good.
All good.
Now, ensure we treat the case where A contains numbers > N? Possibly not.
Now, final code.
One more note: The input format: "First line contains T, the number of test cases. Each test case consists of N, K and P followed by K integers in next line denoting the array A." So they say "followed by K integers in next line". But it's not guaranteed that they are all on one line? They could be across multiple lines? Usually they are on one line, but could be across multiple lines. However, we just read K integers sequentially, ignoring line breaks, using scanf. That's fine.
Now, implement.
Now, I'll produce final answer.
But before finalize, let's consider potential pitfalls in binary search implementation: The condition while(lo <= hi) and updating ans and hi/lo correctly yields the minimal x satisfying condition.
Now, test boundary: lo=1, hi=N=1, mid=1, present computed, if present>=P then ans=1 else lo=2, hi=1 break. Since we already check P <= N-K, if N=1, K=0, P=1, present=1, ans=1. If K=1, then total_present=0, we would have output -1 earlier. So good.
Now, when N is large and K is 0, binary search will find ans = P, but we could shortcut: if K==0, answer = P. Could add an optimization: if K==0: printf("%lld\n", P); But not necessary.
Now, regarding integer types: P is long long, but we compare with present (long long). In binary search, we compute present as long long. Good.
Now, about reading: Use %d for N, K, %lld for P? P is long long, so %lld. In output, ans is int, use %d.
Now, check if any compiler issues: Use #include and #include and #include . Typically ok.
Now, code.
One more edge: The removed numbers might be unsorted and have duplicates. We sort and dedup, but if there are duplicates, the effective K reduces, but the input K we initially read may be larger than the distinct count. However, the condition we used total_present = N - distinct_K. This matches actual present numbers. But we also used K in the loop reading A of size original K, but after dedup we set K = A.size(). That's fine.
But we also used original K to read exactly that many numbers. That is correct.
Now, consider if some removed numbers are outside [1,N]. They should not exist, but if they do, then they are not in the bag; removing them does nothing. So they should not be counted as removed. But our dedup only deduplicates; we still count them as removed if they are within [1,N]? Actually we count them in the removed set, which would incorrectly reduce present count. So we should filter out numbers not in [1,N]. However, problem statement likely guarantees they are from 1..N. But to be extra safe, we could filter: after reading, we can keep only numbers between 1 and N. But that might be overkill. I think it's fine.
Given the constraints, we can trust input.
Now, we need to output -1 if no such number exists. Already handled.
Now, run through sample: 2 test cases, we get 3 and -1.
Now, finalize.
Wait, I'm re-reading the problem: "Watson gives to Sherlock a bag of numbers [1, 2, 3 ... N] and then he removes K numbers A1, A2 ... AK from the bag. He now asks Sherlock to find the P'th smallest number in the bag." So P'th smallest among the numbers remaining. Output P'th smallest number. If no such number exists output -1.
In sample 2, N=5, K=2, A=[1,3], remaining [2,4,5]. P=4, no 4th smallest, output -1. So our logic works.
Now, final code.
But there is a nuance: The binary search method relies on the monotonicity of f(x) = x - count_removed(≤ x). f is non-decreasing and increases by 1 at each present number, stays same at removed numbers. So it's correct.
Now, also note that we used upper_bound to count numbers <= mid. That's fine.
Now, test with huge K and N: K = 100000, N = 1e9. Sorting takes time, but okay.
Now, I'll write the final solution in C++.
Potential improvements: Could use iterative scanning method to avoid binary search and binary search inside, but not needed.
Now, final answer: Provide explanation and code.
But the problem might be part of a competitive programming environment where they expect fast I/O. We'll use scanf/printf. Also, possibly use ios_base sync false? Not needed.
Now, final code:
#include <bits/stdc++.h>
using namespace std;
int main() {
int T;
scanf("%d", &T);
while (T--) {
int N, K;
long long P;
scanf("%d %d %lld", &N, &K, &P);
vector A(K);
for (int i = 0; i < K; ++i) {
scanf("%d", &A[i]);
}
sort(A.begin(), A.end());
A.erase(unique(A.begin(), A.end()), A.end());
K = A.size();
long long total_present = N - K;
if (P > total_present) {
printf("-1\n");
continue;
}
int lo = 1, hi = N;
int ans = N; // fallback
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int cnt_removed = upper_bound(A.begin(), A.end(), mid) - A.begin();
long long present = mid - cnt_removed;
if (present >= P) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
printf("%d\n", ans);
}
return 0;
}
Now, I'll also consider the case where N is 0? Not possible.
Now, think about possibility that after dedup, K may become > original? No.
Now, check if we need to use long long for mid? Not.
Now, confirm that the answer is within [1,N] and present. Good.
Now, finalize.
One more thought: The problem states "Large input files. Use scanf instead of cin." So our code uses scanf.
Now, output as int.
Now, test with some random cases to ensure no off-by-one.
Let's write a small script mentally:
Case: N=6, K=3, A=[2,4,6], P=3. Present: 1,3,5. Sorted: 1,3,5 => 3rd smallest = 5. Binary search:
lo=1, hi=6.
mid=3: cnt_removed = upper_bound([2,4,6],3) -> index of first >3 is 1 (since 4>3, 2<=3) => cnt=1, present=2 <3 => lo=4.
mid=5: cnt_removed = upper_bound(...,5) -> first >5 is index 2 (6) => cnt=2, present=3 >=3 => ans=5, hi=4.
mid=4 (since after? Actually after lo=4, hi=4, mid=4: cnt_removed = upper_bound(...,4) -> first >4 is index 2 (6?) Actually array [2,4,6]; upper_bound(4) returns first element >4 => index of 6 -> 2, so cnt=2, present=2 <3 => lo=5, hi=4 break. ans=5. Good.
Case: N=6, K=3, A=[1,3,5], P=3. Present: 2,4,6 => 3rd =6. Binary search:
mid=3: cnt_removed = upper_bound([1,3,5],3) -> index of first >3 is 2 (5) => cnt=2 (since 1,3<=3? Actually upper_bound returns first >3, so elements <=3: 1 and 3, count=2). present=1 <3 -> lo=4.
mid=5: cnt_removed = upper_bound(...,5) -> first >5 is index 3 => cnt=3, present=2 <3 -> lo=6.
mid=6: cnt_removed = upper_bound(...,6) -> first >6 is end => cnt=3, present=3 >=3 => ans=6, hi=5. Good.
Case: N=6, K=3, A=[1,2,3], P=1. Present:4,5,6 => 1st=4. Binary search:
mid=3: cnt=3 present=0 <1 -> lo=4.
mid=5: cnt_removed = upper_bound(...,5) -> index of first >5 is 3 (since all <=5? Actually array [1,2,3] all <=5, so cnt=3) present=2 >=1 => ans=5? But minimal should be 4. We got ans=5? Wait we need to check: At mid=5, present=5-3=2 >=1, so ans=5, but then hi becomes 4? We need to ensure binary search continues to find minimal. Let's step carefully:
lo=1, hi=6.
mid=3 -> present=0 <1, lo=4.
Now lo=4, hi=6.
mid=5 -> present=2 >=1 -> ans=5, hi=4.
Now lo=4, hi=4.
mid=4 -> present? cnt_removed = upper_bound(...,4) -> first >4 is index 3 (since all <=4) -> cnt=3, present=4-3=1 >=1 -> ans=4, hi=3.
Now lo=4, hi=3 -> exit. ans=4. Good. So binary search finds 4 correctly.
Thus algorithm works.
Now, final code ready.
But one more nuance: We used int for N, but N can be up to 1e9, which fits in 32-bit signed int (max 2,147,483,647). So int is fine. On some platforms int may be 16-bit? Not in modern C++. So okay.
Now, potential memory: vector A with up to 1e5 ints, fine.
Now, edge: When N - K is large and P is large, binary search may need many steps but fine.
Now, final answer. ```cpp
#include
#include
#include
using namespace std;
int main() {
int T;
scanf("%d", &T);
while (T--) {
int N, K;
long long P;
scanf("%d %d %lld", &N, &K, &P);
code
vector<int> A(K);
for (int i = 0; i < K; ++i)
scanf("%d", &A[i]);
// sort and remove possible duplicates (input guarantees distinct, but safe)
sort(A.begin(), A.end());
A.erase(unique(A.begin(), A.end()), A.end());
K = (int)A.size();
long long remaining = N - K;
if (P > remaining) {
printf("-1\n");
continue;
}
int lo = 1, hi = N;
int ans = N; // will be overwritten
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
// count removed numbers <= mid
int cnt_rem = upper_bound(A.begin(), A.end(), mid) - A.begin();
long long present = mid - cnt_rem; // numbers from 1..mid that are present
if (present >= P) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
printf("%d\n", ans);
}
return 0;