求助
查看原帖
求助
37507
phoneix楼主2022/2/11 17:03

求助各位大佬:为什么由小到大的递推就不能找出正确答案,而由大到小就可以呢?

我想通过贪心,先找到1在哪里,然后看更大的那一个在左还是右,然后不断的往过跑。

我的代码如下:

vector是实现stack的功能的,但是因为要排序,就用了vector

ans+1表示 Mex l,r 中没有出现过的最小正整数。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
//#include <stack>
using namespace std;
#define re register
#define il inline
const int maxn=4e6+7;
il int R(){
	int x=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){
		if(ch=='-')f=-1;
		ch=getchar();
	}
	while('0'<=ch&&ch<='9'){
		x=x*10+ch-'0';
		ch=getchar();
	}
	return x*f;
}
il void W(int x){
	if(x<0){
		x=-x;
	}
	if(x>9){
		W(x/10);
	}
	putchar('0'+x%10);
	return;
}

int a[maxn];
int f[maxn];
vector <int> lf,ri;
bool in[maxn];
int main( ){
//	freopen("qwq0.in","r",stdin);
	int n=R();
	int var=0;
	for(int i=1;i<=n;i++){
		a[i]=R();
		if(a[i]==1){
			var=i;
		}
	}
	for(int i=var-1;i>=1;i--){
		lf.push_back(a[i]);
	}
	for(int i=var+1;i<=n;i++){
		ri.push_back(a[i]);
	}
	sort(lf.begin(),lf.end(),greater<int>());
	sort(ri.begin(),ri.end(),greater<int>());//最小的在最后,可以pop_back(); 
	for(int i=1;i<=n;i++){
		f[i]=R();
	}
	in[1]=true;
	int ans=1,mnum=2;
	//ans::答案 
	int l=var-1,r=var+1;
	if(f[1]<=1){
		printf("1");
		return 0;
	}
	for(int i=2;i<=n;i++){
		while(!lf.empty()&&in[lf.back()]==true){
			lf.pop_back();
		}
		while(!ri.empty()&&in[ri.back()]==true){
			ri.pop_back();
		}
		if(!lf.empty()&&lf.back()<ri.back()){
			while(a[l]!=ans+1&&l>=1){
				if(ans+1>f[i]){
					cout<<i;
					return 0;
				}
				in[a[l]]=true;
				l--,i++;
			}
			ans++;		
		}else if(!ri.empty()){
			while(a[r]!=ans+1&&r<=n){
				if(ans+1>f[i]){
					cout<<i;
					return 0;
				}
				in[a[r]]=true;
				r++,i++;
			}
			ans++;
		}
		if(ans+1>f[i]){
			cout<<i;
			return 0;
		}
		while(in[ans+1]==true){
			ans++;
		}
	}
//	abort();
	puts("0");
	return 0;
}
2022/2/11 17:03
加载中...