题解 | #kotori和素因子#

kotori和素因子

https://www.nowcoder.com/practice/7b1c858a3e7a41ed8364178979eaae67

非递归深度优先遍历思路
#include<iostream>
#include<unordered_set>
#include<stack>
#include<vector>
using namespace std;

int n;
int a[1010];
int mi = 1e9, temp = 0;
unordered_set<int> s;
stack<int> f;
vector<vector<int>> h;

bool primer(int x) {
    for (int i = 2; i * i <= x; ++i) {
        if (x % i == 0) {
            return false;
        }
    }
    return true;
}

void findi(int& x, int& i) {
    if (x < n - 1) {
        if(s.count(h[x][i])){
            ++i;
        }
        else if (i < h[x].size()) {
            f.push(i);
            s.insert(h[x][i]);
            temp += h[x][i];
            i = 0;
            ++x;  //深度遍历
        } else {
            if (!f.empty()) {
                i = f.top() + 1;
                s.erase(h[x-1][f.top()]);
                temp -= h[x-1][f.top()];
                f.pop();
            }
            --x;//到底回溯
        }
    } else {
        if(s.count(h[x][i])){
            ++i;
        }
        else if (i < h[x].size()-1) {
            temp += h[x][i];
            mi = min(mi, temp);
            temp -= h[x][i];
            ++i;
        } else {
            if (i == h[x].size()-1) {
                temp += h[x][i];
                mi = min(mi, temp);
                temp -= h[x][i];
            }
            i = f.top() + 1;
            temp -= h[x-1][f.top()];
            s.erase(h[x-1][f.top()]);
            f.pop();
            --x;
        }
    }
}

int main() {
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) {
        scanf("%d", &a[i]);
    }
    for(int i=0;i<n;++i){
        h.push_back(vector<int>());
        for(int j=2;j<=a[i];++j){
            if(primer(j)&&(a[i]%j)==0)
                h[i].push_back(j);
        }
    }
    int x = 0, i = 0;
    while (1) {
        findi(x, i);
        if (x <= 0 && i >= h[0].size()) break;
    }
    if (mi == 1e9) printf("%d", -1);
    else printf("%d", mi);
    return 0;
}


全部评论

相关推荐

04-18 15:58
已编辑
门头沟学院 设计
kaoyu:这一看就不是计算机的,怎么还有个排斥洗碗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务