思路比较简单,主要是定义了一个分数类,并用的set来存储结果,保证结果的顺序性和互异性。为了使set正常工作,需要重载运算符<;代码如下:
#include<iostream>
#include<set>
#include<algorithm>
using namespace std;
int gcd(int a, int b) {//寻找最大公约数的函数;
int r;
if (a < b) {
r = b;
b = a;
a = r;
}
while (a != 0 && b != 0) {
r = a%b;
a = r;
if (b > r) {
a = b;
b = r;
}
}
return a;
}
class Frac {//自定义的分数类;
public:
int a;
int b;
double value;
Frac(int aa, int bb) :a(aa), b(bb) {
value = a*1.0 / b;
}
friend bool operator<(const Frac&a, const Frac&b) {//重载的<运算符;
return a.value < b.value;
}
friend ostream& operator<<(ostream&output, const Frac&f) {//重载<<运算符,方便结果输出;
output << f.a << '/' << f.b;
return output;
}
};
void getResult(int n){
set<Frac>res;//存放结果的set;
int temp,a,b;
for(int i=0;i<=n;++i)
for (int j = i + 1; j <= n; ++j) {
temp = gcd(i, j);
a = i;
b = j;
a /= temp;
b /= temp;//进行约分,并存入set;
res.insert(Frac(a, b));
}
for (set<Frac>::iterator it = res.begin();it!=res.end();++it) {
cout << *it << endl;
}
cout << "1/1" << endl;
}
int main()
{
int n;
cin >> n;
getResult(n);
return 0;
}
时间复杂度分析:需要检测的组合个数为(O(n^2)),set插入需要时间为(lg 1 + lg 2 + lg 3 + ... +lg (n^2) = O(4 lg n));
所以总体时间复杂度为(O(n^2));