• 计蒜客_合法分数的组合


    思路比较简单,主要是定义了一个分数类,并用的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));

    如有不当,欢迎指正 :)
  • 相关阅读:
    C++类的成员函数的指针和mem_fun适配器的用法
    C++ RTTI的使用
    C++特殊工具与技术之RTTI
    Linux组件封装之五:生产者消费者问题
    Linux组件封装之四:RAII实现MutexLock自动化解锁
    Linux组件封装之三:Thread
    Linux组件封装之二:Condition
    Linux组件封装之一:MUtexLock
    C++ socket与Flex as3通信的沙盒问题解决
    CentOS搭建PHP环境
  • 原文地址:https://www.cnblogs.com/lif323/p/7411976.html
Copyright © 2020-2023  润新知