(1)0/1背包问题
用回溯法实现0/1背包问题的求解,问题的规模N取4,8,16,32…,计算到单次求解过程不超过3分钟为止,要求随机生成物品的重量和价值,物品重量的取值范围110,物品价值的取值范围150,背包的容量C可由用户输入。
运行结果
分析
使用的是dfs ,在dfs中,设置三个参数,第一个是体积,第二个是价值,第三个是从该参数到数组末尾中选择数据。
减枝:
1.如果体积超过容量 return.
2.如果从当前物品到最后一个物品全取不爆空间,则可以return.
代码
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<time.h>
using namespace std;
const int N = 1e7 + 10;
int n;
int V;
int maxs;
int allv,allw;
int vI[N],wI[N];
struct Box
{
int vi,wi;
}st[N];
bool pt[N];
void dfs(int u,int ww,int t )
{
if(u > V) return;
if(vI[n]-vI[t-1] + u < V )
{
ww+=wI[n]-wI[t-1];
maxs = max(ww,maxs);
return ;
}
maxs = max(maxs,ww);
for(int i = t; i <= n ; i ++ )
if(!pt[i])
{
pt[i] = true;
dfs(u + st[i].vi,ww+st[i].wi,i + 1);
pt[i] = false;
}
}
int main()
{
n = 4;
cout <<" input V " << endl;
cin >> V;
while(n < 1e7 +10)
{
clock_t start,ends;
maxs = 0;
memset(pt,0,sizeof pt);
memset(vI,0,sizeof vI);
memset(wI,0,sizeof wI);
for(int i = 1; i <= n ; i ++ )
{
int v = rand()%11;
int w = rand()%51;
if(v == 0) v = 1;
if(w == 0) w = 1;
allv+=v;
allw+=w;
st[i] = {v,w};
vI[i] = v;
vI[i] += vI[i-1];
wI[i] = w;
wI[i] += wI[i-1];
}
if(V > allv) maxs = allw;
else
{
start = clock();
dfs(0,0,1);
ends = clock();
ends -= start;
}
if(n <32)
{
for (int i = 0; i < n ; i ++ )
cout << st[i].vi << " " << st[i].wi <<endl;
}
cout << "max is "<<maxs <<endl;
n*=2;
if(ends > 180000) break;
}
return 0;
}
(2)奇怪的比赛
某电视台举办了低碳生活大奖赛。题目的计分规则相当奇怪:每位选手需要回答10个问题(其编号为1到10),越后面越有难度。答对的,当前分数翻倍;答错了则扣掉与题号相同的分数(选手必须回答问题,不回答按错误处理)。每位选手都有一个起步的分数为10分。某获胜选手最终得分刚好是N分,N可由用户输入,分别设计蛮力算法和回溯算法,编写程序,输出所有可能的答题情况。记录程序运行时间,比较你设计的回溯法与蛮力法相比在理论上和实际运行结果上的优势。
程序输入输出示例:
输入:100
输出:
1011010000
0111010000
0010110011
输入:92
No Answer
分析
1.如果在回答第n个题目的时候,分数为负数,且分数小于查询的分数,return
2.在回答第n 题时,n - 10的题目全答对,分数仍然小于查询的分数,return
运行时间图
代码
// 题目2 蛮力法
#include<iostream>
#include<cstring>
#include<algorithm>
#include<time.h>
using namespace std;
int n;
//方法1
void Violence(int t)
{
bool it = true;
for(int i = 0; i < n ; i ++)
{
int ans = 10;
for(int j = 0; j <= 9; j ++ )
{
if(i>>j & 1)
{
ans*=2;
}
else
{
ans -= (j + 1);
}
}
if(t==ans)
{
it = false;
for(int j = 0; j <= 9; j ++ )
{
if(i>>j & 1) cout << 1 << " ";
else cout << 0 <<" ";
}
}
}
if(it) cout << "No Answer" <<endl;
}
//方法2
void Pruning(int t)
{
bool it = true;
for(int i = 0; i < n ; i ++)
{
int ans = 10;
for(int j = 0; j <= 9; j ++ )
{
if(i>>j & 1)
{
ans*=2;
}
else
{
ans -= (j + 1);
}
if(ans < 0 && ans < t) break;
if((ans<<(9-j + 1)) < t) break;
}
if(t==ans)
{
it = false;
for(int j = 0; j <= 9; j ++ )
{
if(i>>j & 1) cout << 1 << " ";
else cout << 0 <<" ";
}
}
}
if(it) cout << "No Answer" <<endl;
}
int main()
{
n = 1 << 10;
int t ;
cin >> t;
clock_t start,ends;
start = clock();
Violence(t);
ends = clock();
cout <<"暴力花费的时间 :" << ends - start <<endl;
start = clock();
Pruning(t);
ends = clock();
cout <<"减枝花费的时间 :" << ends - start <<endl;
return 0;
}