萌新求问关于栈溢出MLE
  • 板块学术版
  • 楼主Mo默Sh笙
  • 当前回复3
  • 已保存回复3
  • 发布时间2022/11/15 20:58
  • 上次更新2023/10/27 02:50:39
查看原帖
萌新求问关于栈溢出MLE
189485
Mo默Sh笙楼主2022/11/15 20:58

RT,求问栈溢出大概要多少层递归才会炸?

代码才2^21层,500MB空间就炸了……还是说我炸的是数组空间

题目

#include<bits/stdc++.h>
using namespace std; 
int n,k;
long long money,cnt;
long long a[41];
long long ans[1<<21];
bool cmp(long long x,long long y)
{
	return x>y;
}
int half_find(long long cost)
{
	int l=1,r=k;
	while(l<=r)
	{
		int m=(l+r)>>1;
		if(ans[m]>=cost) l=m+1;
		else r=m-1;
	}
	return r;
}
void first_half_dfs(int l,int r,long long rest)
{
	if(rest<0) return ;
	if(l>r)
	{
		ans[++k]=rest;
		return ;
	}
	first_half_dfs(l-1,r,rest-a[l]);                                                                                   
	first_half_dfs(l+1,r,rest);
	return ;
}
void second_half_dfs(int l,int r,long long cost)
{
	if(cost>money) return ;
	if(l>r)
	{
		int v=half_find(cost);		
		cnt+=v;
//		cout<<cnt<<" "<<cost<<" "<<v<<endl;
		return ;
	}
	second_half_dfs(l+1,r,cost+a[l]);                                                                                   
	second_half_dfs(l+1,r,cost);
	return ;
}
int main()
{
	scanf("%d%lld",&n,&money);
	for(int i=1;i<=n;i++)
	{
		scanf("%lld",&a[i]);
	}
	sort(a+1,a+n+1,cmp);
	first_half_dfs(1,n/2,money);
	sort(ans+1,ans+k+1,cmp);
	second_half_dfs(n/2+1,n,0);
	printf("%lld",cnt);
	return 0;
}
2022/11/15 20:58
加载中...