Links: https://ac.nowcoder.com/acm/contest/102/C
Source: Cattle-off network
Title Description
We define a value of an interval is the second largest number of it's elements, and of course an interval has at least two elements.
Given an array A with
n elements and a number
k, can you find the value of the
k
th largest interval?
Enter a description:
The first line contains an integer number T, the number of test cases.
For each test case :
The first line contains two integer numbers n,k(2 ≤ n ≤ 10
5,1 ≤ k ≤ n(n−1)/2), the number of test cases.
The second lines contains n integers A
i(1 ≤ A
i ≤ 10
9), the elements of array A.
Output Description:
For each test case print the value of the kth
largest interval.
Example 1
Explanation
For the sample input, there are three intervals.rd
Interval [1 2 3] has value 2.
Interval [2 3] has value 2.
Interval [1 2] has value 1.
So the 3
largest interval is [1 2] whose value is 1.
ideas: seeking k-th largest, the present problem and POJ3579 similar dichotomy then greedy test, foot emulated, at least two elements, to maintain a queue of two elements, for example:
. 1 2 . 3 4, 2, 3 select, select 1 or 2, the front, rear choose 3 or 4, that is, four kinds of
typedef long long LL; const int maxm = 1e5+10; int buf[maxm], n, q[maxm]; LL k; bool check(int x) { LL sum = 0, front = 0, rear = 0, last = -1; for(int i = 0; i < n; ++i) { if(buf[i] >= x) q[front++] = i; if(front - rear > 1) { sum += (q[rear] - last) * (n - i); last = q[rear++]; } } return sum >= k; } int main() { int T; scanf("%d", &T); while(T--) { scanf("%d%lld", &n, &k); for(int i = 0; i < n; ++i) scanf("%d", &buf[i]); int l = 1, r = 1e9, ans, mid; while(l <= r) { mid = (l + r) >> 1; if(check(mid)) { ans = mid; l = mid + 1; } else r = mid - 1; } printf("%d\n", ans); } return 0; }