跳到正文

题解

「LYHOI R4」拆分问题 题解

Starry_Knight约 1 分钟
原文
文章信息与版本

文章信息

发布
2026年7月25日
收录
2026年7月25日
更新
2026年11月17日
篇幅
约 1 分钟

版本

  1. v1当前

DFS 都学过吧?不会的请自己查阅资料。

这题就是用 DFS 来做,像我们的全排列一样。

那么首先就从小的数开始进行 DFS,到后面加大即可。

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e1+7;
int n,ans,a[N];
void dfs(int l,int sum,int x){
	if(sum==n){
		cout<<n<<"=";
		for(int i=1;i<=x-1;i++){
			if(i>1) cout<<"+";
			cout<<a[i]; 
		}
		cout<<'\n';
		ans++;
		return ;
	}
	for(int i=l;i<=min(n-sum,n-1);i++){
		a[x]=i;
		dfs(i,sum+i,x+1);
	}
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin>>n;
    dfs(1,0,1);
    cout<<"total="<<ans; 
    return 0;
}
原文