51nod1686 第K大区间 【二分】
来源:互联网 发布:网络教育学籍查询 编辑:程序博客网 时间:2024/05/22 00:34
题目:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1686
题意:
定义一个区间的值为其众数出现的次数。
现给出n个数,求将所有区间的值排序后,第K大的值为多少。
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
分析:
二分答案x,然后判断是否有不少于k个区间的众数的次数大于等于x。
判断的时候是枚举左端点,然后找最靠左的右端点,使得这个区间内的某个数出现的次数不小于x,那么以左端点为区间的符合要求的个数就有n-r+1个。这样求和后如果个数不少于k个,说明这个x至少是第k大数。继续二分。
代码:
#include <bits/stdc++.h>using namespace std;const int N=1e5+9;int n,k;int cnt[N];struct node { int x,id,val;} a[N];int cmp(const node& x,const node& y) { if(x.x==y.x)return x.id<y.id; return x.x<y.x;}int cmp1(const node& x,const node& y) { return x.id<y.id;}int check(int x) { memset(cnt,0,sizeof(cnt)); long long ans=0; int r=0; for(int i=1; i<=n; i++) { while(1) { int t=a[r].val; if(t!=-1&&(cnt[t]>=x||r>n))break; r++; t=a[r].val; cnt[t]++; } ans=ans+n-r+1; cnt[a[i].val]--; } return ans>=k;}int main() { //freopen("in.txt","r",stdin); scanf("%d%d",&n,&k); for(int i=1; i<=n; i++) scanf("%d",&a[i].x),a[i].id=i; sort(a+1,a+n+1,cmp); a[0].val=a[0].x=-1; for(int i=1; i<=n; i++) { //排序后离散化 if(a[i].x!=a[i-1].x)a[i].val=i; else a[i].val=a[i-1].val; } sort(a+1,a+n+1,cmp1); int l=1,r=n; while(l<=r) { int mid=(l+r)>>1; if(check(mid))l=mid+1; else r=mid-1; } printf("%d",l-1); return 0;}
0 0
- 二分 51Nod1686 第K大区间
- 51nod1686 第K大区间 【二分】
- 51nod1686 第K大区间
- 51nod1686 第K大区间
- 51nod 1686 第K大区间【离散化+二分】
- 51nod 1686 第K大区间 二分好题
- 51nod 1686 第K大区间(二分 尺取)
- 【二分+Two Pointers】51Nod 1686 第K大区间
- 区间第K大
- 第K大区间
- 区间第k大
- HDU 4417 (二分 + 区间第k大)
- [复习]整体二分求区间第K大
- 51nod 1686 第K大区间 (二分+滑动窗口+离散化)
- 【51nod】 第K大区间2(二分+树状数组)
- 51Nod【1686】——1686 第K大区间(尺取+二分)
- 解题报告:51nod 1686 第K大区间 二分+尺取
- 51nod 1686-第K大区间(离散化+二分+尺取)
- iOS 保持界面流畅的技巧
- Vue过渡(动画)- transition组件
- [leetcode] 520. Detect Capital
- 终端最常用快捷键
- 跟踪(Tracking)资料汇总
- 51nod1686 第K大区间 【二分】
- SSH三大框架的工作原理及流程
- Mahout的协同过滤推荐的关键概念与理论
- 在C语言头文件中“”与<>有什么区别?
- Android无法在外置存储上创建文件夹,file.mkdirs()一直返回false
- Android 获取系统版本号,设备品牌等
- DTP取上一日
- 【REDIS】redis.conf中文版(基于2.4)
- Swift 关于cocoapods导入 桥连接 无法找到的错误。