1103. Integer Factorization (30)

来源:互联网 发布:mysql修改数据库列名 编辑:程序博客网 时间:2024/06/05 02:44

dfs遍历剪枝来做,必须规定有序,不然绝对超时

#include<iostream>#include<vector>#include<cmath>#include<algorithm>using namespace std;int N, K, P,s_num;vector<int> f;vector<int> path;vector<int> temp_path;void dfs(int n, int k,int low)//dfs遍历,low是为了保证递增序{    if (n == 0 && k == 0)    {        path = temp_path;        //mi = te;        return;    }    if (n<=0||k<=0||n<f[low]*k) return;//剪枝,不然会超时    for (int t = low;t <= s_num;t++)    {        temp_path.push_back(t);        dfs(n-f[t],k-1,t);        temp_path.pop_back();    }}int main(){    cin >> N >> K >> P;    s_num = pow(N, (double)1 / P);    f.resize(s_num + 1);    for (int t = 0;t <= s_num;++t)    dfs(N, K,1);    if (path.empty()) cout << "Impossible" << endl;    else    {        sort(path.rbegin(), path.rend());        printf("%d = %d^%d", N, path[0], P);        for (unsigned int t = 1;t < path.size();t++)            printf(" + %d^%d", path[t], P);        cout << endl;    }}
0 0
原创粉丝点击