URAL 1005 Stone Pile (DFS)

本文介绍了一个使用深度优先搜索(DFS)解决背包问题的C语言程序示例。该程序的目标是最小化两组物品重量之间的差异,通过递归地考虑每个物品是否放入背包中的一组来实现。定义了宏用于简化绝对值和无穷大的表示,并使用数组存储物品重量及总重量等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#define ABS(x) ( (x) > 0 ? (x) : -(x) )
#define INF (1 << 31 - 1)
#define MAX_STONES (20 + 1)
#define MAX_WEIGHT (100000)


int numOfStones;
int weights[MAX_STONES];
int totalWeigh;
int minDifferOfWeight = INF;

void DFS(int depth, int currentWeigh){
    if (depth == numOfStones){
        if (ABS(totalWeigh - currentWeigh - currentWeigh) < minDifferOfWeight)
            minDifferOfWeight = ABS(totalWeigh - currentWeigh - currentWeigh);
        return;
    }

    DFS(depth + 1, currentWeigh + weights[depth + 1]);
    DFS(depth + 1, currentWeigh);
}
int main()
{

    scanf("%d", &numOfStones);
    int indexOfStone;
    for (indexOfStone = 1; indexOfStone <= numOfStones; indexOfStone++){
        scanf("%d", &weights[indexOfStone]);
        totalWeigh += weights[indexOfStone];
    }

    DFS(0, 0);

    printf("%d", minDifferOfWeight);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值