【csp模拟赛九】--dfs3

这道题贪心错误:直接dfs就行,枚举新开一个还是往之前的里面塞

贪心代码(80):

#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<iostream>
#define N 10500
using namespace std;
int read()
{
	int x=0,f=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){ if(ch=='-')f=-1;ch=getchar(); }
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x*f;
}
int n,W,ans,wei,len1,len2,tot,c[N];
bool vis[N];
struct node{ int val,id; }a[N],b[N];
bool cmp1(const node &a,const node &b)
{
	return a.val>b.val;
}
bool cmp2(const node &a,const node &b)
{
	return a.val<b.val;
}
int main()
{
	#ifdef yilnr
	#else
	freopen("climb.in","r",stdin);
	freopen("climb.out","w",stdout);
	#endif
	n=read(); wei=read();
	for(int i=1;i<=n;i++)
	{
		a[i].val=read(); b[i].val=a[i].val;
		a[i].id=b[i].id=i;
	}
	sort(a+1,a+n+1,cmp2);
	sort(b+1,b+n+1,cmp1);
	while(tot!=n)
	{
		ans++;
		W=wei;
		len2=1;
		while(W>=b[len2].val && len2<=n)
		{
			if(!vis[b[len2].id])
			{
				W-=b[len2].val; vis[b[len2].id]=1; tot++;
			}
			len2++;
		}
		for(int i=1;i<=n;i++)c[i]=a[i].val;
		len1=upper_bound(c+1 , c+n+1 , W) - c;
		len1--;
		while(W>=a[len1].val && len1>=1)
		{
			if(!vis[a[len1].id])
			{
				W-=a[len1].val; vis[a[len1].id]=1; tot++;
			}
			len1--;
		}
	}
	printf("%d\n",ans);
	fclose(stdin);fclose(stdout);
	return 0;
}
/*
5 1996
1
2
1994
12
29
*/

 

代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;

int n,m;
int a[50];
int ans,sta[50];

inline void DFS(int opt,int cnt) {
	if(cnt >= ans) return ;
	if(opt == n + 1) {
		ans = min(cnt,ans);
		return ;
	}
	for(int i = 1;i <= cnt;i ++) {
		if(sta[i] + a[opt] <= m) {
			sta[i] += a[opt];
			DFS(opt + 1,cnt);
			sta[i] -= a[opt];
		}
	}
	sta[cnt + 1] = a[opt];
	DFS(opt + 1,cnt + 1);
	sta[cnt + 1] = 0;
}

int main() {
	freopen("climb.in","r",stdin);
	freopen("climb.out","w",stdout);
	
	scanf("%d%d",&n,&m);
	for(int i = 1;i <= n;i ++)
		scanf("%d",&a[i]);
	sort(a + 1,a + n + 1,greater<int>());
	ans = n; DFS(1,1);
	printf("%d",ans);
	
	fclose(stdin);
	fclose(stdout);
	return 0;
}

 

转载于:https://www.cnblogs.com/yelir/p/11600361.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值