集训 T3-难题

大致题意:

  • 求方程 (a_1+a_2+...+a_n=m) 的非负整数解有几个。

基本思路:

  • 深搜,虽然看起来可能会超时,但是对于100%的数据,0<=n,m<32767,结果<32767,说明搜的次数并不多,
  • 所以就能愉快的用深搜啦。
  • (dfs(num,cnt))中的(num)(m)(cnt)(n)
  • (cnt)等于(1)就说明只剩下一个(a_1)了,答案个数加(1)就行咯。
  • 否则就循环(0)(num),然后(dfs(num-i,cnt-1))

Code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <list>
using namespace std;
#define R read()
#define GC getchar()
#define ll long long
#define ull unsigned long long
#define INF 0x7fffffff
#define LLINF 0x7fffffffffffffff
ll read(){
    ll s=0,f=1;
    char c=GC;
    while(c<'0'||c>'9'){if(c=='-')f=-f;c=GC;}
    while(c>='0'&&c<='9'){s=s*10+c-'0';c=GC;}
    return s*f;
}
void fre(){
    freopen("problem.in","r",stdin);
    freopen("problem.out","w",stdout);
}
int n,m;
int ans;
void dfs(int num,int cnt){//num为题中的m,cnt为题中的n
    if(cnt==1){//如果只剩下一个(只有一个就说明方案数是1),那么就直接++ans
        ++ans;
        return ;
    }
    for(int i=0;i<=num;++i){//接着深搜,搜索每一个解
        dfs(num-i,cnt-1);
    }
}
int main(){
    fre();
    n=R;m=R;
    dfs(m,n);//搜索
    printf("%d",ans);//输出
    return 0;
}
原文地址:https://www.cnblogs.com/FUXyao/p/12906025.html