lightoj 1014

本文介绍了一种优化的深度优先搜索(DFS)算法来分解整数的质因数,通过判断到根号n的方式减少计算量,并直接输出结果避免额外排序。适用于寻找较小范围内的质因数。

判断到根号n即可,另外使用dfs输出,不需要另开数组再排序。


#include<cmath>
#include<cstdio>
int P, L, len, cnt;
void dfs(int dep){
    if(dep > len) return;
    if(dep > L){
        if(P % dep == 0){
            if(cnt == 1) printf("%d", dep), cnt = 2;
            else printf(" %d", dep);
            dfs(dep+1);
            if(P/dep != dep && P/dep > L) {
                if(cnt == 1) printf(" %d", P/dep), cnt = 2;
                else printf(" %d", P/dep);
            }
        }else dfs(dep+1);
    }else {
        dfs(dep+1);
        if(P % dep == 0 && P/dep > L) {
            if(cnt == 1) printf("%d", P/dep), cnt = 2;
            else printf(" %d", P/dep);
        }
    }
}
int main(){
    int t, CASE(0);
    scanf("%d", &t);
    while(t--){
        scanf("%d%d", &P, &L);
        if(L >= P - L) printf("Case %d: impossible\n", ++CASE);
        else {
            P -= L;
            len = sqrt(P);
            printf("Case %d: ", ++CASE);
            cnt = 1;
            dfs(1);
            printf("\n");
        }
    }

转载于:https://www.cnblogs.com/wangzhili/p/3950243.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值