HihoCoder - 1483 - 区间价值

/*
https://vjudge.net/problem/HihoCoder-1483

题意:给出n个数,然后定义一个v(l,r)为下标区间[l,r]中相同的点对数,
如对于1,1,1这个序列来说,v(1,2)=1,v(1,3) =3,v(1,1)=0。
现在要求所有n*(n+1)/2个区间的价值第k小的是多少。

二分+尺取法 
*/
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <cmath>
#include <stack>
#include <string>
#include <sstream>
#include <map>
#include <set>
#define pi acos(-1.0)
#define LL long long
#define ULL unsigned long long
#define inf 0x3f3f3f3f
#define INF 1e18
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
using namespace std;
typedef pair<int, int> P;
const double eps = 1e-10;
const int maxn = 1e6 + 5;
const int N = 1e4 + 5;
const int mod = 1e8;

int T, n;
LL k;
int a[maxn],  c[maxn];
map<int, int>mp;
int judge(LL x)
{
	LL sum = 0, cnt = 0; // sum记录相同对数少于x的区间个数 
	int l = 1;
	for (int i = 1; i <= n; i++)
		c[i] = 0;		
	for (int r = 1; r <= n; r++){ //c[i]记录[l,r]中,数i有多少个 
		sum += c[a[r]]; // 区间加上数a[r]后,sum += c[a[r]] 
		c[a[r]]++;	// 然后区间内 c[a[r]]的个数加1 
		while (sum > x){ // 如果此时区间对数大于x 
			c[a[l]]--;	// 尺取法,将左边界l一点一点右移 
			sum -= c[a[l]]; // 对数减去 c[a[l]] 
			l++;
		}
		cnt += r - l + 1;
	}
	return cnt >= k;
}
int main(void)
{
//	freopen("in.txt", "r", stdin);
	cin >> T;
	while (T--){
		cin >> n >> k;
		mp.clear();
		int tot = 0, num;
		for (int i = 1; i <= n; i++){
			cin >> num;
			if (!mp.count(num))
				mp[num] = ++tot;	 //离散化方便后面统计   
			a[i] = mp[num];
		}
		LL l = 0, r = (LL)n*(n-1)/2;
		while (l < r){
			LL mid = (l + r) >> 1;
			if (judge(mid))	//答案在区间里面,则更小范围的区间是[l, mid]  	
				r = mid;
			else l = mid + 1;	//答案不在区间在答案在[mid+1, r]区间  
		} 
		cout << r << endl;// 此题 ans = r = l 	
	}

	return 0;
}












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值