和题解差不多的代码为什么样例都过不了
  • 板块P1441 砝码称重
  • 楼主atqiae
  • 当前回复1
  • 已保存回复1
  • 发布时间2024/4/12 16:08
  • 上次更新2024/4/12 16:35:09
查看原帖
和题解差不多的代码为什么样例都过不了
389200
atqiae楼主2024/4/12 16:08

看了@hsfzLZH1的题解,然后自己试着打了一遍,感觉和题解给的代码没什么区别,但样例都过不去,求助

题解代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=22;
const int maxm=2010;
int n,m,a[maxn],ans,tot,ret;
bool tf[maxn],f[maxm];
void dp()
{
    memset(f,0,sizeof f);f[0]=true;ans=0;tot=0;
    for(int i=0;i<n;i++)
    {
        if(tf[i])continue;
        for(int j=tot;j>=0;j--)if(f[j]&&!f[j+a[i]])f[j+a[i]]=true,ans++;
        tot+=a[i];
    }
    ret=max(ans,ret);
}
void dfs(int cur,int now)
{
    if(now>m)return;
    if(cur==n){if(now==m)dp();return;}
    dfs(cur+1,now);
    tf[cur]=true;
    dfs(cur+1,now+1);
    tf[cur]=false; 
} 
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)scanf("%d",a+i);
    dfs(0,0);
    printf("%d\n",ret);
    return 0;
}

我的代码:

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int maxn,ans,n,m,a[25];
bool o[2005],w[25];
void dp()
{
	memset(o,0,sizeof(o));
	int sum=0;
	o[0]=1;
	maxn=0;
	for(int i=1;i<=n;i++)
	{
		if(w[i]==1)
		{
			continue;
		}
		for(int j=sum;j>=0;j--)
		{
			if(o[sum]==1&&o[sum+a[i]]==0)
			{
				o[sum+a[i]]=1;
				maxn++;
			}
		}
		sum+=a[i];
	}
	ans=max(ans,maxn);
}
void dfs(int now,int x)
{
	if(x>m)
	{
		return;
	}
	if(now==n+1)
	{
		if(x==m)
		{
			dp();
		}
		return;
	}
	dfs(now+1,x);
	w[now]=1;
	dfs(now+1,x+1);
	w[now]=0;
}
int main()
{
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
	}
	dfs(1,0);
	cout<<ans;
	return 0;
}
2024/4/12 16:08
加载中...