To Add or Not to Add CodeForces - 231C

原题链接
考察:双指针
思路:
  将原数组排序后,枚举每一个\(a[i]\),求使\((j,i)\)全部变为\(a[i]\)的最长左边界\(j\),当\(a[i]\)变小时,\(j\)只会往更左扩展.

Code

#include <iostream> 
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 100010;
int n,k,a[N];
int main()
{
	scanf("%d%d",&n,&k);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	sort(a+1,a+n+1);
	LL sum = 0;
	int res = 0,val;
	for(int i=n,j=n;i>=1;i--)
	{
		while(j>=1&&sum+a[i]-a[j]<=k)
		{
			sum+=(LL)a[i]-a[j];
			j--;
		}
		int len = i-j;
		if(len>res) res = len,val = a[i];
		else if(len==res&&a[i]<val) val = a[i]; 
		sum-=(LL)(a[i]-a[i-1])*(i-j-1);
	}
	printf("%d %d\n",res,val);
	return 0;
}
posted @ 2021-07-24 09:34  acmloser  阅读(26)  评论(0编辑  收藏  举报