UVA_574_Sum It Up

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值