请给出一份修改完毕后`Solve`函数的c++代码
时间: 2023-11-21 17:45:02 浏览: 50
根据你的要求,我修改了 `Solve` 函数的 C++ 代码,以节省内存消耗。以下是修改后的代码:
```cpp
#include <iostream>
using namespace std;
int n, m;
inline int gcd(int a, int b)
{
if (!b) return a;
return gcd(b, a % b);
}
struct Frac
{
int fz, fm;
double val;
void simplify()
{
register int g = gcd(fz, fm);
fz /= g;
fm /= g;
val = (double)fz / (double)fm;
}
void init(int fm_, int fz_)
{
fm = fm_;
fz = fz_;
simplify();
}
Frac plus(Frac a)
{
register int gfm = a.fm * fm;
register int gfz = a.fz * fm + fz * a.fm;
Frac ans;
ans.init(gfm, gfz);
ans.simplify();
return ans;
}
Frac times(int a)
{
register int gfm = fm;
register int gfz = fz * a;
Frac ans;
ans.init(gfm, gfz);
ans.simplify();
return ans;
}
};
int Solve(int cnt, int last, const Frac& sum)
{
if (cnt == n)
{
if (sum.fm - sum.fz == 1 && sum.fm >= last)
{
return 1;
}
return 0;
}
if (sum.val >= 1)
{
return 0;
}
Frac lst;
lst.init(last, 1);
Frac add = lst.times(n - cnt + 1);
Frac t = sum.plus(add);
if (t.val == 1)
return 1;
if (t.val < 1)
{
return 0;
}
lst.init(m, 1);
add = lst.times(n - cnt);
t = sum.plus(add);
if (t.val >= 1)
{
return 0;
}
int count = 0;
for (register int i = last; i <= m; ++i)
{
Frac temp;
temp.init(i, 1);
count += Solve(cnt + 1, i, sum.plus(temp));
}
return count;
}
int main()
{
cin >> n >> m;
cout << Solve(1, 2, {0, 1, 0.00}) << endl;
return 0;
}
```
在修改后的代码中,我将 `sum` 参数改为了 `const Frac& sum`,即通过常量引用传递。这样做可以避免对 `sum` 结构体进行复制操作,减少了内存消耗。同时,结构体的成员函数也保持了原来的逻辑不变。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)