洛谷 P1025 [NOIP 2001 提高组] 数的划分(深搜剪枝)

深搜剪枝,dfs基础,加上回溯可以输出路径

AcCode:

#include<iostream>
#include<vector>
using namespace std;
int n, k, res = 0;

void dfs(int sum, int h, int be){
	if(h == k){
		if(sum == n){
			res++;
		}
		return ;
	}
	
	for(int i = be; i + sum <= n; i++){
		dfs(sum + i, h + 1, i);
	}
}

int main(){
	cin >> n >> k;
	dfs(0, 0, 1);	
	cout << res;
	return 0;
} 

输出路径版Code:

#include<iostream>
#include<vector>
using namespace std;
int n, k;
vector<int> path;
vector<vector<int> > res;
void dfs(int sum, int h, int be){
	if(h == k){
		if(sum == n){
			res.push_back(path);
		}
		return ;
	}
	
	for(int i = be; i + sum <= n; i++){
		path.push_back(i);
		dfs(sum + i, h + 1, i);
		path.pop_back();
	}
}

int main(){
	cin >> n >> k;
	dfs(0, 0, 1);	
	for(int i = 0; i < res.size(); i++){
		for(int j = 0; j < k; j++){
			cout << res[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
} 
posted @ 2025-03-06 17:04  Yuhhhhh  阅读(9)  评论(0)    收藏  举报