双指针求调(c++)并玄2关
查看原帖
双指针求调(c++)并玄2关
877599
EX_EXCRSE楼主2025/1/19 07:36

代码如下

#include<bits/stdc++.h>
using namespace std;
const int N=5*1e4+10;
long long a[N],ans=0,ans_=0,mn=INT_MAX,ll,rr,jjboom,zx=0;
map<long long ,long long>ids,cshattt;//cshattt的作用 = cnt
int main() {
	long long n;
	cin>>n;
	for(int i=1; i<=n; i++) {
		cin>>a[i];
		cin>>ids[a[i]];//a[i]=x[i],ids为该坐标对应的id
		if(++cshattt[ids[a[i]]]==1) {
			ans++;
		}
	}
	sort(a+1,a+1+n);
	cshattt.clear();
	long long l=1,r=1;
	if(ans_<ans) {
		cshattt[ids[a[1]]]++;
		if(cshattt[ids[a[1]]]==1) {
			ans_++;
		}
	}
	while(l<=n&&r<=n) {//双指针
		if(ans_<ans) {
			r++;
			//cout<<ids[a[4]]<<endl;
			cshattt[ids[a[r]]]++;
			//cout<<cshattt[ids[a[1]]]<<endl;
			if(cshattt[ids[a[r]]]==1) {
				ans_++;
			}
			zx=1;
		} else {
			l++;
			if(zx==1) {
				r--;
				zx--;
			}
			long long sum=a[r]-a[l];
			if(ans_==ans) {
				if(mn>sum) {
					mn=sum;
					//ll=l;
					//rr=r;
					jjboom=ans_;
				}
			}
			cshattt[ids[a[l]]]--;
			if(cshattt[ids[a[l]]]==0) {
				ans_--;
			}
			
		}
		//cout<<cshattt[ids[a[3]]]<<" "<<l<<" "<<r<<endl;
	}
	cout<<mn;
	return 0;
}
2025/1/19 07:36
加载中...