C/C++教程

Addition Chains

本文主要是介绍Addition Chains,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

6136: Addition Chains

时间限制(普通/Java):1000MS/3000MS     内存限制:65536KByte

 

描述

An addition chain for n is an integer sequence <a0, a1,a2,...,am> 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. 

样例输入

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

本题可深搜剪枝和广搜,广搜记录每次循环的数列入队,每次拿数列最后一个数字加每一个数字,符合条件的入队第一次符合题目要求就输出并结束。

用深搜的话更快,可以深搜外套层循环确定数列长度最多为多少,然后开始深搜,长于该长度的队列舍弃;每次循环该数列长度加一,直到搜到符合的;

代码(广搜)

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main()
 4 {
 5     ios_base::sync_with_stdio(false);
 6     cin.tie(nullptr);
 7     cout.tie(nullptr);
 8     int n;
 9     while (cin>>n,n)
10     {
11         if(n==1)
12         {
13             cout<<1<<endl;
14             continue;
15         }
16         vector<int>v;
17         v.push_back(1);
18         queue<vector<int> >q;//记录每次队列情况
19         q.push(v);
20         while (!q.empty())
21         {
22             vector<int>temp=q.front();
23             q.pop();
24             int len=temp.size();
25             int hou=temp.back();//该数列最后一个值
26             for(int i=len-1;i>=0;i--)
27             {
28                 int he=temp[i]+hou;
29                 if(he==n)//如果符合就输出
30                 {
31                     for(auto k:temp)
32                     {
33                         cout<<k<<" ";
34                     }
35                     cout<<he<<endl;
36                     goto Last;//结束
37                 }
38                 else if(he<n&&he>temp.back())
39                 {
40                     vector<int>te=temp;
41                     te.push_back(he);
42                     q.push(te);
43                 }
            }
        }
46         Last:;
47     }
48     return 0;
49 }        

 

这篇关于Addition Chains的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!