2248:Addition Chains
描述
An addition chain for n is an integer sequence with the following four properties:
a0 = 1
am = n
a0 < a1 < a2 < … < am-1 < am
For each k (1<=k<=m) there exist two (not necessarily different) integers i and j (0<=i, j<=k-1) with ak=ai+aj
You are given an integer n. Your job is to construct an addition chain for n with minimal length. If there is more than one such sequence, any one is acceptable.
For example, <1,2,3,5> and <1,2,4,5> are both valid solutions when you are asked for an addition chain for 5.
输入
The input will contain one or more test cases. Each test case consists of one line containing one integer n (1<=n<=100). Input is terminated by a value of zero (0) for n.
输出
For each test case, print one line containing the required integer sequence. Separate the numbers by one blank.
Hint: The problem is a little time-critical, so use proper break conditions where necessary to reduce the search space.
样例输入
5
7
12
15
77
0
样例输出
1 2 4 5
1 2 4 6 7
1 2 4 8 12
1 2 4 5 10 15
1 2 4 8 9 17 34 68 77
这道题用BFS和DFS都可以做,需要注意的是DFS的剪枝条件,一不小心就容易WA。
下面直接贴代码
(DFS+剪枝)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,k;
int a[110];
bool b[110]; //标记数组
bool dfs(int step)
{
memset(b,0,sizeof(b));
if(step>k)
{
if(a[k]==n) return 1;
return 0;
}
for(int i=step-1; i>=1; i--)
for(int j=i; j>=1; j--)
if(a[j]+a[i]<=n && !b[a[i]+a[j]])
{
if(a[i]+a[j]<=a[step-1])
return 0; //一个剪枝 保证a[]是递增的序列
a[step]=a[i]+a[j];
b[a[step]]=1;
if(dfs(step+1))
return 1; //超过深度->进行判断->退出
}
return 0;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
a[1]=1,a[2]=2;
while(cin>>n&&n)
{
if(n==1)
cout<<1<<endl;
else if(n==2)
cout<<1<<" "<<2<<endl;
else
{
for(k=3; k<=100; k++) //遍历经过多少steps可以达到n - 该步数一定是最短的
{
if(dfs(3))
{
for(int i=1; i<=k; i++)
cout<<a[i]<<" ";
cout<<endl;
break;
}
}
}
}
return 0;
}
(BFS)
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstdlib>
using namespace std;
int cnt=0;
int n;
class node
{
public:
int id;
int val;
int pre;
node(int a=-1,int b=-1,int c=-1):id(a),val(b),pre(c){}
};
vector<node>path;
void output_path(int id)
{
if(path[id].pre==-1)
{
cout<<path[id].val<<" ";
return ;
}
else
{
output_path(path[id].pre);
cout<<path[id].val<<" ";
}
}
void bfs()
{
queue<node>q;
q.push(node(0,1,-1));
path.push_back(node(0,1,-1));cnt++;
while(!q.empty())
{
node now = q.front();
q.pop();
for(int i = now.id; i!=-1; i = path[i].pre)
{
int tmp = now.val + path[i].val;
if(tmp == n)
{
output_path(now.id);
cout<<n<<endl;
return;
}
if(tmp < n)
{
node next = node(cnt, tmp, now.id);
path.push_back(next);cnt++;
q.push(next);
}
}
}
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0);
while(cin>>n&&n)
{
if(n==1)
cout<<1<<endl;
else
{
cnt=0;path.clear();
bfs();
}
}
return 0;
}