PAT1103 Integer Factorization (30)(DFS:回溯)

题意:

给三个正整数N、K、P,将N表示成K个正整数(可以相同,递减排列)的P次方和,如果有多种方案,选择底数n1+…+nk最大的方案,如果还有多种方案,选择底数序列的字典序最大的方案

思路:

这题看时间和n的大小就知道估计是用dfs做,不过我回溯烂的很,没写出来,下面是参考别人代码写的。

注意codeblock中pow返回时会损失精度,pow(5,2)如果用int显示为24,解决方法是+0.5或者用double表示,vs和vc中没有这个问题。

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<cmath>
#include<queue>
#include<map>
#include<set>
using namespace std;
const int maxn = 505;
int n, k, p;
vector<int> tempAns,v,ans;
int maxFacSum = -1;

void init() {
	for (int i = 0; i <= pow(n, 1.0 / p); i++) {
		v.push_back(pow(i, p));
	}
}

void dfs(int index, int tempSum, int tempK, int facSum) {
	if (tempSum == n&&tempK == k) {
		if (facSum > maxFacSum) {
			ans = tempAns;
			maxFacSum = facSum;
		}
		return;
	}
	if (tempSum > n || tempK > k) return;
	if (index >= 1) {
		tempAns.push_back(index);
		dfs(index, tempSum + v[index], tempK + 1, facSum + index);
		tempAns.pop_back();
		dfs(index - 1, tempSum, tempK, facSum);
	}
}

int main() {
	scanf("%d%d%d", &n, &k, &p);
	init();
	dfs(v.size()-1, 0,0,0);
	if (maxFacSum == -1) {
		printf("Impossible\n");
		return 0;
	}
	printf("%d = ",n);
	for (int i = 0; i < ans.size(); i++) {
		if (i != 0)
			printf(" + ");
		printf("%d^%d", ans[i], p);
	}
	return 0;
}

 

posted @ 2018-07-12 20:34  seasonal  阅读(85)  评论(0)    收藏  举报