跳到正文

题解

P4799 [CEOI2015 Day2]世界冰球锦标赛 题解

small_juju约 4 分钟
原文
文章信息与版本

文章信息

发布
2021年7月22日
收录
2026年10月20日
更新
2026年11月14日
篇幅
约 4 分钟
获赞
5
题目
P4799

版本

  1. v1当前

一道折半搜索好题。

看了一下题面,认为这道题不是一道裸背包的题目,不一会写出来,然后数据范围都没看就交上去了,下面贴一下背包代码。

C++
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#define SIZE 1000005
#define int unsigned long long
using namespace std;
int n,m,w[SIZE],f[SIZE],ans;
signed main(){
	ios::sync_with_stdio(false);cin.tie(0);cout.tie();
	cin>>n>>m;
	for(register int i=1;i<=n;i++) cin>>w[i];
	f[0]=1;
	for(register int i=1;i<=n;i++){
		for(register int j=m;j>=w[i];j--){
			f[j]+=f[j-w[i]]; //计数类01背包板子
		}
	}
	for(register int i=0;i<=m;i++) ans+=f[i]; //最后统计答案,将所有的可行方案都累加
	cout<<ans;
	return 0;
}

这样,你就可以拿了50分!

现在,你会觉得用暴搜,但空间与时间不让你过去,这时候我们发现每个比赛只有两种情况,看和不看,这样搜索时间复杂度是 O(2n)O(2^n) ,肯定过不了。

于是折半搜索法就可以用到了。

思想:我们现在可以将所有比赛的序列分成两个部分,分别对这两部分进行搜索,然后用数组来存储可能的方案与花费,在排序使其有序,最后用在合并,二分搜索查找可行解,统计答案累加,得出最终的答案。

放个代码:

C++
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<vector>
#define SIZE 105
#define int unsigned long long
using namespace std;
int n,m,w[SIZE],ans=0;
vector<int> a,b;
void dfs_1(int st,int ed,int sum){ //统计左边界可能发生的最小花费,用a来存。 
	if(sum>m) return; //如果说你的花费大于了预算花费,即不符合,退出 
	if(st>ed){
		a.push_back(sum); //如果左指针大于右指针,即都遍历完了,统计存放数组 
		return;
	}
	dfs_1(st+1,ed,sum),dfs_1(st+1,ed,sum+w[st]); //选或不选 
	return;
}
void dfs_2(int st,int ed,int sum){ //统计右边界可能发生的最小花费,用b来存
	if(sum>m) return;
	if(st>ed){
		b.push_back(sum);
		return;
	}
	dfs_2(st+1,ed,sum),dfs_2(st+1,ed,sum+w[st]);
	return;
}
signed main(){
	ios::sync_with_stdio(false);cin.tie(0);cout.tie();
	cin>>n>>m;
	for(register int i=1;i<=n;i++) cin>>w[i];
	dfs_1(1,n>>1,0),dfs_2(n>>1|1,n,0); //折半搜索 
	
	sort(a.begin(),a.end()); //排序 
	
	for(register int i=0;i<b.size();i++) 
		ans+=upper_bound(a.begin(),a.end(),m-b[i])-a.begin(); //二分查找找到花费比剩下钱还少的方案数,累加答案 
	
	cout<<ans;
	return 0;
}
原文
存档评论1 条抓取于