星期七补星期一的课,所以今天是星期八,上次说过星期八写博客,今天就来了。
二进制枚举是比较偏的算法,知道的人不多。其底层原理就是通过二进制中的1和0代表每种物品选与不选的情况。如果需要选取的物品为20, 则它所以可能的情况为2的20次方,即1 048 576,所以二进制枚举只能用来处理数据量较小的题目,尽管比较局限,但是它处理这类题目的程序相较于搜索是比较容易写出的,而且也很好理解。
例题1蓝桥杯和为T
问题描述
从一个大小为n的整数集中选取一些元素,使得它们的和等于给定的值T。每个元素限选一次,不能一个都不选。
输入格式
第一行一个正整数n,表示整数集内元素的个数。
第二行n个整数,用空格隔开。
第三行一个整数T,表示要达到的和。
输出格式
输出有若干行,每行输出一组解,即所选取的数字,按照输入中的顺序排列。
若有多组解,优先输出不包含第n个整数的;若都包含或都不包含,优先输出不包含第n-1个整数的,依次类推。
最后一行输出总方案数。
样例输入
5
-7 -3 -2 5 9
0
样例输出
-3 -2 5
-7 -2 9
2
#include<iostream>
int a[25];
using namespace std;
int main() {
int n, k, sum, cnt = 0;
cin>>n;
for(int i = 0; i < n; ++i) {
cin>>a[i];
}
cin>>k;
for(int i = 1; i < (1 << n); ++i) {
sum = 0;
for(int j = 0; j < n; ++j) {
if(i & (1 << j)) {
sum +=a[j];
}
}
if(sum == k) {
for(int j = 0; j < n; ++j) {
if(i & (1 << j)) {
cout<<a[j]<<' ';
}
}
cout<<"\n";
cnt++;
}
}
cout<<cnt;
return 0;
}
例题2 HDU吉姆的天平
Jam’s balance
Problem Description
Jim has a balance and N weights. (1≤N≤20)
The balance can only tell whether things on different side are the same weight.
Weights can be put on left side or right side arbitrarily.
Please tell whether the balance can measure an object of weight M.
Input
The first line is a integer T(1≤T≤5), means T test cases.
For each test case :
The first line is N, means the number of weights.
The second line are N number, i’th number wi(1≤wi≤100) means the i’th weight’s weight is wi.
The third line is a number M. M is the weight of the object being measured.
Output
You should output the “YES"or"NO”.
Sample Input
1
2
1 4
3
2
4
5
Sample Output
NO
YES
YES
题意:有一个天平,n个砝码,每次给出一个数k,问能否用天平秤出这个重量。
这题乍一看和第一题差不多,实际上有很多不同
题解:需要注意的就是砝码可以在天平两边放,类似于高中学的左码右物,然后游码往右偏移了一部分。举个例子比较好理解,比如有两个砝码 1, 3, 那么天平不仅可以秤出1,3,4,还能秤出3-1=2这个重量。
#include<iostream>
#include<cstring>


1204

被折叠的 条评论
为什么被折叠?



