题目链接: 点击打开链接
题目大意: 给出n个数字,要求设计一个尺子,刻度尽量少,长度尽量短,能够把n个数字都表示出来。刻度不超过7个,第一个刻度为0.
思路: 隐式树搜索,bfs
分析:
学习了网上大牛的代码,搜索树的状态为一个set,记录所有刻度;以及一个status,用二进制记录能表示的数字。对于一个状态,遍历该状态的所有刻度,每个刻度加上或减去一个数字可以得到一个新刻度。为这个刻度创建一个新状态,新状态可以表示更多的数字。当搜索到一个状态能表示所有数字的时候,更新答案。
代码:
#include <cstdio>
#include <cmath>
#include <set>
#include <queue>
#include <algorithm>
#include <memory.h>
using namespace std;
const int maxn = 50 + 5;
const int maxi = 1000000 + 10;
struct node
{
int cur_status; // 用二进制记录当前能表示的数字
set<int> scales; // 记录所有刻度
};
int n, max_number, status;
int numbers[maxn], n_index[maxi];
set<int> ans;
void init()
{
for (int i = 0; i < n; ++i)
scanf("%d", &numbers[i]);
sort(numbers, numbers + n);
// 去重
n = unique(numbers, numbers + n) - numbers;
max_number = numbers[n-1];
// 记录每个数字的序号,初始化最佳答案ans
ans.clear(); ans.insert(0);
memset(n_index, -1, sizeof(n_index));
for (int i = 0; i < n; ++i) {
n_index[numbers[i]] = i;
ans.insert(numbers[i]);
}
// 最终状态
status = (1 << n) - 1;
}
bool check_scale(int scale, node cur) // 判断是否要增加该刻度
{
if (cur.scales.find(scale) != cur.scales.end()) return false;
if (scale < 0 || scale > max_number) return false;
return true;
}
void add_node(int scale, node cur, queue<node>& q) // 向队列增加一个结点
{
node new_node = cur;
new_node.scales.insert(scale); // 增加新刻度
for (set<int>::iterator iter = cur.scales.begin(); iter != cur.scales.end(); ++iter) // 增加能表示的数字
{
int number = abs(scale - *iter);
if (n_index[number] != -1) new_node.cur_status |= 1 << n_index[number];
}
if (new_node.cur_status != cur.cur_status) q.push(new_node);
}
void scan_and_add_node(int scale, node cur, queue<node>& q) // 遍历所有要表示的数字,获得新刻度,增加队列结点
{
for (int i = 0; i < n; ++i)
{
if (cur.cur_status & (1 << i)) continue;
if (check_scale(scale - numbers[i], cur))
add_node(scale - numbers[i], cur, q);
if (check_scale(scale + numbers[i], cur))
add_node(scale + numbers[i], cur, q);
}
}
void bfs()
{
node init_node; init_node.cur_status = 0; init_node.scales.insert(0);
queue<node> q; q.push(init_node);
while (!q.empty())
{
node top = q.front(); q.pop();
if (top.cur_status == status) // 结束条件
{
if (top.scales.size() < ans.size())
ans = top.scales;
else if (top.scales.size() == ans.size() && *top.scales.rbegin() < *ans.rbegin())
ans = top.scales;
return;
}
for (set<int>::iterator iter = top.scales.begin(); iter != top.scales.end(); ++iter)
scan_and_add_node(*iter, top, q);
}
}
void output()
{
printf("%d\n", ans.size());
for (set<int>::iterator iter = ans.begin(); iter != ans.end(); ++iter)
printf("%d ", *iter);
printf("\n");
}
int main()
{
int kase = 1;
while (scanf("%d", &n) && n != 0)
{
init();
bfs();
printf("Case %d:\n", kase++);
output();
}
return 0;
}