基准时间限制:1 秒 空间限制:131072 KB 分值: 40
难度:4级算法题
Input
第一行两个数n和k(1<=n<=100000,k<=n*(n-1)/2) 第二行n个数,0<=每个数<2^31
Output
一个数表示答案。
Input示例
4 2 1 2 3 2
Output示例
2
﹡ LH
(题目提供者)
C++的运行时限为:1000 ms ,空间限制为:131072 KB
示例及语言说明请按这里
允许其他 AC 的用户查看此代码,分享代码才能查看别人的代码并有机会获得勋章
首先a[i]较大,无法用数组存储每个数出现的次数,因此我们可以考虑离散化
齐次我们可以考虑二分答案,然后check是否能找到符合当前答案的“合法区间”
但是这时你会发现复杂度会是n^2(logn),还是不够本题的时间限制,呢我们怎么办呢? 放弃?(呢就放弃呗)
放弃啥啊,我们可以考虑每一个右端点,然后移动左端点来统计“合法区间”,其实就是尺取,。。
复杂度大约为n*logn ,简直完美。。
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<string>
#include<math.h>
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<functional>
using namespace std;
typedef long long ll;
#define inf 1000000000
#define mod 1000000007
#define maxn 1006000
#define PI 3.1415926
#define lowbit(x) (x&-x)
#define eps 1e-9
int b[maxn], a[maxn], cnt[maxn], n, k;
bool work(int x)
{
int i, count = 0;
memset(cnt, 0, sizeof(cnt));
int l = 1, r = 1;
while (r <= n)
{
cnt[a[r]]++;
if (cnt[a[r]] >= x)
{
count += n - r + 1;
cnt[a[l]]--;l++;
while (cnt[a[r]] >= x && l < r)
{
count += n - r + 1;
cnt[a[l]]--;l++;
}
}
r++;
if (count >= k)
return 1;
}
return 0;
}
int main(void)
{
int i, j, x, ans;
scanf("%d%d", &n, &k);
for (i = 1;i <= n;i++)
scanf("%d", &a[i]), b[i]=a[i];
sort(b + 1, b + n + 1);
int num = unique(b + 1, b + n + 1)-(b+1);
for (i = 1;i <= n;i++)
a[i] = lower_bound(b + 1, b + num + 1, a[i]) - (b + 1);
int l = 1, r = n;
while (l <= r)
{
int mid = (l + r) / 2;
if (work(mid))
ans = mid, l = mid + 1;
else
r = mid - 1;
}
printf("%d\n", ans);
return 0;
}