Day6 - 牛客102C
链接:https://ac.nowcoder.com/acm/contest/102/C
来源:牛客网
题目描述
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 kth largest interval?
输入描述:
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 ≤ 105,1 ≤ k ≤ n(n−1)/2), the number of test cases.
The second lines contains n integers Ai(1 ≤ Ai ≤ 109), the elements of array A.
输出描述:
For each test case print the value of the kth
largest interval.
示例1
说明
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.
思路:求第k大,本题和POJ3579相似,二分然后贪心检验,尺取法,最少2个元素,就维护2个元素的队列,例如:
1 2 3 4, 选择2,3时,前面可选择1或2, 后面可选择3或4,就是4种
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; }