#include<iostream>
#include<sstream>
#include<string>
#include<vector>
#include<list>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
#pragma warning(disable:4996)
using std::cin;
using std::cout;
using std::endl;
using std::stringstream;
using std::string;
using std::vector;
using std::list;
using std::pair;
using std::set;
using std::multiset;
using std::map;
using std::multimap;
using std::stack;
using std::queue;
using std::priority_queue;
using std::sort;
using std::next_permutation;
void print(const int &target,const vector<pair<int, int>>&factor)
{
bool flag = false;
for (size_t i = 0; i < factor.size(); i++)
{
for (size_t j = 0; j < factor[i].second; j++)
{
if (flag)
{
cout << '+';
}
else
{
flag = true;
}
cout << factor[i].first;
}
}
cout << endl;
}
void backtrack(const int &sum,const vector<pair<int, int>>&value, int i, int target, vector<pair<int, int>>&factor,bool &flag)
{
for (; i < value.size(); i++)
{
//count=能取最多多少次这个数
int j = target / value[i].first < value[i].second ? target / value[i].first : value[i].second;
target -= j*value[i].first;
factor.push_back({value[i].first,j});
for (; j > 0; j--)
{
if (target)
{
backtrack(sum,value, i + 1, target, factor,flag);
}
else
{
flag = true;
print(sum,factor);
}
target += value[i].first;
factor[factor.size() - 1].second--;
}
factor.pop_back();
}
}
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int target, n;
while (cin >> target >> n)
{
if (!target&&!n)
{
break;
}
vector<pair<int, int>>value{ {0,0} };
while (n--)
{
int num; cin >> num;
if (num == value[value.size() - 1].first)
{
value[value.size() - 1].second++;
}
else
{
value.push_back({num,1});
}
}
printf("Sums of %d:\n",target);
vector<pair<int,int>>factor;
bool flag = false;
backtrack(target,value,1,target,factor,flag);
if (!flag)
{
cout << "NONE" << endl;
}
}
return 0;
}
UVA_574_Sum It Up
最新推荐文章于 2017-06-26 07:52:33 发布