社区讨论

双指针求调(c++)并玄2关

P3029[USACO11NOV] Cow Lineup S参与者 1已保存回复 0

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
0 条
当前快照
1 份
快照标识符
@m62tw651
此快照首次捕获于
2025/01/19 07:37
去年
此快照最后确认于
2025/11/04 11:20
4 个月前
查看原帖
代码如下
CPP
#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;
}

回复

0 条回复,欢迎继续交流。

正在加载回复...