*[topcoder]LCMSetEasy

http://community.topcoder.com/stat?c=problem_statement&pm=13040

DFS集合全排列+LCM和GCD。但事实上,有更简单的算法,列在下面,就是观察到不能整除x的对我们无效。

#include <vector>

#include <iostream>

using namespace std;



class LCMSetEasy {

public:

    string include(vector <int> S, int x) {

        vector<int> vec;

        if (includeRe(S, x, 0, vec))

            return "Possible";

        else

            return "Impossible";

    }

    

    bool includeRe(const vector<int> &S, int x, int i, vector<int> &vec) {

        if (i == S.size()) {

            int r = lcm(vec);

            if (r == x)

                return true;

            return false;

        }

        vec.push_back(S[i]);

        bool res = includeRe(S, x, i + 1,vec);

        vec.pop_back();

        if (res)

            return true;

        res = includeRe(S, x, i + 1,vec);

        return res;

    }

    

    int lcm(vector<int> vec) {

        if (vec.size() == 0)

            return 1;

        int tmp = vec[0];

        for (int i = 1; i < vec.size(); i++) {

            tmp = lcm(tmp, vec[i]);

        }

        return tmp;

    }

    

    int lcm(int a, int b) {

        int c = gcd(a, b);

        return a * b /c;

    }

    

    int gcd(int a, int b) {

        if (a % b == 0)

            return b;

        int tmp = a % b;

        return gcd(b, tmp);

    }

};

  

string include(vector <int> S, int x) {

        int r = 1;

        for (int i = 0; i < S.size(); i++) {

            if (x % S[i] == 0) {

                r = lcm(r, S[i]);

            }

        }

        if (r == x)

            return "Possible";

        else

            return "Impossible";

    }

  

你可能感兴趣的:(topcoder)