Siukwan Program

http://siukwan.sinaapp.com/

1103. Integer Factorization (30)

1.根据题目的特点,n的最大值不超过400,可以使用深度遍历搜索答案

2.加入限制条件进行剪枝,如i的p次方不能大于n-k+1,因为剩下的数至少均为1,剩下还需要k-1个数需要进行分配,每个数至少分配为1,共k-1,所以i的p次方最大只能为n-(k-1)=n-k+1,而最大值不能超过上一次分配的。


//#include<string>
//#include <iomanip>
#include<vector>
#include <algorithm>
//#include<stack>
#include<set>
#include<queue>
#include<map>
//#include<unordered_set>
#include<unordered_map>
//#include <sstream>
//#include "func.h"
//#include <list>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
using namespace std;
void dfs(int n, int count, int p,int preNum, vector<int>&ans,int ansSum, vector<pair<int,vector<int>>>&totalAns, vector<vector<int>>&num)
{
	if (n == 0 && count == 0)
	{
		totalAns.push_back({ansSum, ans});
	}
	else if ((n == 0 && count != 0) || (n != 0 && count == 0))
		return;
	else
	{
		for (int i = min(n - count+1,preNum); i >= 1; i--)
		{//进行剪枝
			if (num[i][p - 1] != -1 && num[i][p - 1]<=n-count+1)
			{
				ans.push_back(i);
				ansSum += i;
				dfs(n - num[i][p - 1], count - 1, p,i, ans,ansSum, totalAns, num);
				ansSum -= i;
				ans.pop_back();
			}
		}
	}
}
bool cmp(const pair<int, vector<int>>&a, const pair<int, vector<int>>&b)
{
	if (a.first > b.first)
		return true;
	else if (a.first == b.first)
	{
		for (int i = 0; i < a.second.size(); i++)
		{
			if (a.second[i] > b.second[i]) return true;
			else if (a.second[i] < b.second[i]) return false;
		}

	}
	else return false;
}
int main(void)
{
	
	int n, k, p;
	cin >> n >> k >> p;
	vector<vector<int>> num(401, vector<int>(7, 0));
	for (int i = 1; i < 401; i++)
	{
		num[i][0] = i;
		for (int j = 1; j < 7; j++)
		{
			if (num[i][j - 1] == -1) num[i][j] = -1;
			else
			{
				num[i][j] = num[i][j - 1] * i;
				if (num[i][j] > 400) num[i][j] = -1;
			}
		}
	}
	vector<int> ans(0);
	vector<pair<int,vector<int>>> totalAns(0);
	int ansSum = 0;

	dfs(n, k, p,n, ans,ansSum, totalAns, num);
	sort(totalAns.begin(), totalAns.end(), cmp);
	if (totalAns.size() != 0)
	{
		cout << n << " = ";
		for (int i = 0; i < totalAns[0].second.size(); i++)
		{
			cout << totalAns[0].second[i] << "^" << p;
			if (i != totalAns[0].second.size() - 1)
			{
				cout << " + ";
			}
		}
		cout << endl;
	}
	else 
	{
		cout << "Impossible" << endl;
	}

	return 0;
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jmlikun/article/details/49962483
文章标签: dfs
个人分类: PAT
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

1103. Integer Factorization (30)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭